0

Why do I get an error when I try to set the ImageIcon of this JLabel to something. It returns a null pointer exception. Does anyone know the problem?

public class Window extends JFrame{

    JPanel panel = new JPanel();
    JLabel stick[] = new JLabel[10];    

    Window(){

        super("ThisIsWindow");
        setSize(650,550);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        add(panel);
        panel.setLayout(null);

        stick[5].setIcon(new ImageIcon("stick.gif"));

    }
}

The error occurs on the last line of code that sets stick[5] to stick.gif. Can anyone help?

2 Answers 2

6

Add

stick[5] = new JLabel();

before

stick[5].setIcon(new ImageIcon("stick.gif"));

Basically, you are creating an array that holds 10 references of type JLabel, and those references are referring to nothing (null) at the beginning:

JLabel stick[] = new JLabel[10];

So you need to create 10 instances of JLabel with new JLabel() and let those 10 references pointing to them:

for(int i = 0; i < 10; i++) stick[i] = new JLabel();
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! this helped a lot! i thumbed up and chose this as my answer! :)
0

Is there a JLabel object in stick[5]?

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.