1

I have a list of JLabels and when I go to define the first element on the second line, I am getting the NullPointerException error. Why is this?

JLabel[] labels = new JLabel[16];
labels[0].setText("| Dataset |");

I have looked at other posts relating to this error, but I can't seem to find how they relate to this situation.

Lowenstein
  • 25
  • 3
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Mad Physicist Feb 11 '17 at 04:20
  • `I have looked at other posts relating to this error, but I can't seem to find how they relate to this situation.` At first I didn't believe you, but then I realized that you didn't claim to have actually read any of those posts. Please don't waste our time – Mad Physicist Feb 11 '17 at 04:23
  • It sounds like you need a good intro to Java book. Go buy Head First Java. – Nick Ziebert Feb 11 '17 at 04:26

1 Answers1

1

The first line in your code is just used to initialize an array. The is no element in array after that line. You need to add an instance of JLabel in to labels[0] so that you can use setText() after that. Try below to see the difference:

JLabel[] labels = new JLabel[16];
labels[0] = new JLabel();
labels[0].setText("| Dataset |");
Nam Dam
  • 99
  • 6