Search code examples
nullpointerexceptionjlabelsettext

NullPointerException when initializing JLabel


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.


Solution

  • 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 |");