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?
Add
before
Basically, you are creating an array that holds 10 references of type
JLabel, and those references are referring to nothing (null) at the beginning:So you need to create 10 instances of
JLabelwithnew JLabel()and let those 10 references pointing to them: