我正在为学校项目开发 Java 游戏。当我通过在命令提示符中键入“java game”来运行代码时,出现空指针异常(在 game.play,第 35 行,“gameScreen.tick();”),但是当我在此行添加断点时并使用调试器进行调查,调试器显示正确的对象引用并毫无问题地跟踪程序。我似乎无法弄清楚哪里出了问题......
import javax.swing.*;
public class game implements Runnable {
private screen gameScreen;
public static void main(String[] args) {
// put your code here
game thisGame = new game();
SwingUtilities.invokeLater(thisGame);
thisGame.play();
}
public void run() {
JFrame w = new JFrame();
w.setDefaultCloseOperation(w.EXIT_ON_CLOSE);
gameScreen = new screen();
gameScreen = gameScreen.setUp();
w.add(gameScreen);
w.pack();
w.setLocationByPlatform(true);
w.setVisible(true);
}
public void play() {
while(true) {
try { Thread.sleep(10); }
catch (InterruptedException e) { }
}
gameScreen.tick();
}
}
任何帮助将不胜感激!谢谢。
最佳答案
invokeLater()
是一个异步调用,顾名思义,稍后会被调用。
您的下一行调用 thisGame.play()
,它又会在 10 毫秒后调用 gameScreen.tick()
,此时可能未初始化。
调试器工作的原因是方法调用之间的等待时间可能足够长,以允许 run()
方法初始化 gameScreen
关于java - 程序未通过调试器运行时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29747708/