user5234518
user5234518

Reputation:

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

Upvotes: 3

Views: 192

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200148

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

Upvotes: 1

Maslor
Maslor

Reputation: 1910

From the information you have provided, without knowing the exact error stack trace, I think that the origin of your NullPointerException is at:

contentPane.setLayout(null);

When later on you call the Game instance, having that null field throws the exception.

Upvotes: 0

Related Questions