【发布时间】:2018-11-09 09:46:50
【问题描述】:
所以我正在尝试使用 Eclipse Oxygen.2 在 Java 中编写一个名为 Lights Out Cube 的手持电子游戏,我决定包含一个计时器,以便玩家知道他需要多少时间才能完成游戏。当玩家点击一个名为“开始/重置”的按钮(点击一次后我将其文本更改为“重置”),这是我激活计时器的地方,游戏开始。每次点击后,我都会检查玩家是否完成了游戏,如果完成了,我会停止计时器。如果他想再玩一次,我希望计时器重新开始。请帮帮我:
//here i have a function called checkIfWinning() which does the checking; if there is a winner, the following code is executed to stop the timer
timer.cancel();
timer.purge();
//timer is a publicly declared java.util.Timer
//this is a code snippet for btnStart with "time" recording the time in seconds
time=0;
timer.schedule(new TimerTask()
{
@Override
public void run()
{
time++;
int hours = (int) time / 3600;
int remainder = (int) time - hours * 3600;
int mins = remainder / 60;
remainder = remainder - mins * 60;
int secs = remainder;
timeTaken.setText(String.format("%02d:%02d:%02d",hours,mins,secs));
}
}, 1000,1000);
无论如何,这可以做到吗?还是我必须完全移除计时器?
【问题讨论】:
-
您可以取消当前的
TimerTask,然后提交一个新的。为了能够取消它,您需要在某处保留对任务的引用。另请参阅使用ScheduledExecutorService的替代方法,它类似于 Timer,但更灵活。 -
也许我遗漏了一些非常明显的东西,但你为什么需要这个定时器呢?你不能只记录用户开始的时间和他们结束的时间,然后从另一个中减去一个吗?