我正在编写一项作业,目前一切正常。我不会发布整个内容,而是发布被调用和引用的基本类。
基本上,我的问题是我有一个 GameTimer 类来在我的游戏中启动计时器:
public class GameTimer {
GameViewController gvc = GameFrame.gameViewController;
public static boolean isRunning = false;
public int seconds = 0;
public Timer timer = null;
public TimerTask task = null;
public GameTimer () {
timer = new Timer();
}
public void start() {
task = new TimerTask() {
@Override
public void run() {
gvc.updateTime(seconds);
seconds++;
}
};
timer.scheduleAtFixedRate(task, 1000, 1000);
System.out.println("Task was started");
isRunning = true;
}
public void stop() {
task.cancel();
timer.cancel();
timer.purge();
isRunning = false;
}
public void restart() {
stop();
start();
}
}
基本上,我有不同的模式来扩展 GameModel 并在 GameModel 类中引用我的 GameTimer 实例:
public class GameModel {
public GameTimer game_timer = new GameTimer();
//... Rest of instances and classes
}
public class Mode1 extends GameModel {
public Mode1() {
if(!gamer_timer.isRunning)
game_timer.start();
else
game_timer.restart();
}
//.....Rest of methods
}
public class Mode2 extends GameModel {
public Mode2() {
if(!gamer_timer.isRunning)
game_timer.start();
else
game_timer.restart();
}
//.....Rest of methods
}
基本上,我的游戏是一个 GUI,我有一个下拉框,我可以从中选择模式。我的游戏在运行时立即加载模式 1,但当我选择模式 2 时,它会在我的
上返回 NullPointerException task.cancel();
我在其他一些帖子上读到,您必须在计时器之前取消计时器任务,但是我是否将计时器取消放在任务取消之前
任务.取消
计时器.取消()
它仍然给我相同的 NullPointerException
错误如下:
Exception in thread "AWT-EventQueue-0" Mode2
java.lang.NullPointerException
at GameTimer.stop(GameTimer.java:32) // task.cancel()
at GameTimer.restart(GameTimer.java:39)
at Mode2.<init>(Mode2.java:15)
你能帮我弄清楚为什么任务没有取消吗?
最佳答案
为什么isRunning
是静态的?
Mode1 将其设置为 true。 Mode2 已创建,应该对于 isRunning 读取为 false,但它读取为 true(类变量 = 仅使用一个),因此不调用 start( )> 它调用restart( )并获取NPE,因为它从未启动,因此无法停止。
关于java - 为什么我的 TimerTask.cancel() 返回 NPE ? (JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36523971/