1

I have an array of JLabels, they seem to work. If I do a System.out.print(days[index]); I get the actual information contained and the label is present and works.

When i try to add the label at any index to the panel I'm getting a null pointer exception and I'm not sure why?

public class DrawCalendar extends JPanel{

private JLabel month = new JLabel("Month");
private JLabel[] days = {
    new JLabel("Sunday"),
    new JLabel("Monday"),
    new JLabel("Tuesday"),
    new JLabel("Wednesday"),
    new JLabel("Thursday"),
    new JLabel("Friday"),
    new JLabel("Saturday")
};
    private JPanel dayBoxes;
    private JPanel topLabels;





    public DrawCalendar(int month){

        topLabels.add(days[1]);  //the NullPointerException caused here
        add(topLabels);

    }
}

2 Answers 2

1

topLabels hasn't been instantiated. It is of type JPanel, but it is not a JPanel until

  topLabels = new JPanel();

Until then, it is null.

0
1

Where is private JPanel topLabels; initialized? You probably want something like:

topLabels = new JPanel();

in your DrawCalendar's constructor, or just do it implicitly on the declaration line:

private JPanel topLabels = new JPanel();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.