简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM