Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my code throw a NullPointerException?

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


1 Answers

The solution is not to try to back-reference the Game instance from the Field's constructor. This kind of logic is bad practice anyway and here it tries to access the static field before it is set (from within the codepath of the Game constructor).

You should first create the Field instance, then assign it to Game from a point in code where it's known to exist. So move the line

Game.frame.contentPane.add(this);

to such a place (and replace this with the name of the Field variable).

like image 136
Marko Topolnik Avatar answered Apr 22 '26 17:04

Marko Topolnik