【发布时间】:2013-01-24 20:42:27
【问题描述】:
在我的 Boggle 问题系列中,这是下一个问题。
我需要一个可由玩家自定义的计时器。在 Boggle 游戏开始之前,玩家可以选择 30 到 180 秒之间的时间。我用链接到TimerTask 的Timer 尝试了它,这在游戏的第一次运行中有效,但是当我去更改TimerTask 中的秒数并再次运行时,它说任务很忙或已被取消。实现在游戏开始时重置并具有可自定义时间限制的计时器的最佳方法是什么。 Timer/ TimerTask 可以重置吗?
代码:
类倒计时:
public class CountDown {
Timer timer;
DisplayCountDown displayCountDown;
public CountDown(DisplayCountDown displayCountDown) {
timer = new Timer();
this.displayCountDown = displayCountDown;
timer.schedule(this.displayCountDown, 0, 1000);
}
public DisplayCountDown getDisplayCountDown() {
return displayCountDown;
}
public Timer getTimer() {
return timer;
}
}
类 DisplayCountDown:
public class DisplayCountDown extends TimerTask {
private int seconds = 30;
public void run() {
if(seconds > 0) {
seconds--;
} else {
return;
}
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
public int getSeconds() {
return seconds;
}
}
要重置计时器,我试试这个:
countDown = null;
countDown = new CountDown(displayCountDown);
第二次运行时出现此错误:
Exception in thread "main" java.lang.IllegalStateException: Task already scheduled or cancelled
编辑:怎么了?为什么这会得到如此多的负面声誉?我不是要你们给我一个解决方案,我知道你们讨厌它,这根本不是我想要的……我只是想回到正轨,一个班级的名字就足够了我......为了清楚起见:我不是要求一个完整的解决方案,只是为了一些提示:/
【问题讨论】:
-
您说您尝试重置计时器但收到错误消息。如果您包含显示如何创建/重新启动计时器的代码,您可能会得到一些更好的响应。我认为这是一个很好的问题,只是需要一些润色:+1 来抵消一些反对意见
-
在您的一系列令人困惑的问题中?所以要回答这个问题,我需要回顾一下你的问题?请在您的问题中提供所需信息和任何相关代码。
-
@Windle 谢谢,我编辑了它;)
-
@Mark No no no not not all ;) 这只是另一个问题,因为我最近一直在问很多与 Boggle 相关的问题,但这应该很简单,我已经提供了一些代码;)