java - 程序未通过调试器运行时出现空指针异常

标签 java oop debugging nullpointerexception

我正在为学校项目开发 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/

相关文章:

r - 在browser()中完成和继续之间有什么区别?

debugging - Lagom 调试器 Intellij

java - 写入 .doc 文件

java - 从字符串中获取字节

python - 如果为真 : destruct Class

java - 循环依赖——总是错的?

java - Clojure 与 Java 的互操作 : how to call a class?

java - mybatis 映射器 xml : The content of element type "mapper" must match

Java纸牌游戏: Deck Class help needed

c++ - _ITERATOR DEBUG LEVEL 困惑?