I've got a JFrame
and automatically a content pane generated by Eclipse.
public JPanel contentPane = new JPanel();
public static Game frame;
The main method creates the new frame:
frame = new Game();
frame.setVisible(true);
Creating the new instance:
public Game() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane.setLayout(null);
contentPane.setSize(500, 500);
setContentPane(contentPane);
At the end of this I want to create a new object of my Field.java (which extends JLabel
)
new Field(50, 50, 64, 64);
Field.java:
public Field(int x, int y, int x2, int y2) {
setBounds(x, y, x2, y2);
Game.frame.contentPane.add(this);
}
I hope you can understand what I'm trying to do. When adding the field to the contentPane
of the Game
class, I get a NullPointerException
. I think, contentPane
is null
. But why? And what could I do to avoid this?
Error message:
java.lang.NullPointerException
at Hackbaellchen.Field.<init>(Field.java:23)
at Hackbaellchen.Lemmings.<init>(Game.java:73)
at Hackbaellchen.Lemmings$1.run(Game.java:27)
Field.java:23 is Game.frame.contentPane.add(this);
Game.java:73 is new Field(50, 50, 64, 64);