首先,我对编程很新,所以所有的帮助将不胜感激。我得到了这个代码,其中我使用了java.util.timer,我想在点击某个按钮后重新启动计时器。 当我第一次打开游戏时计时器将启动,40秒后会有一条消息,除了“开始”和“结束”按钮之外的所有游戏按钮都将被禁用。现在我的问题是,如何在成功清理并清除它后重新启动计时器?
public AntInking_GUI() {
timerStart();
}
public void startButton() {
// start button, re-generates a new pattern and re-news the time
enableButtons();
timerStart();
timerSeconds = 0;
timeLeft = 40;
public void timerStart() {
// timer that counts from 40 to 0, if it reaches 0 then the game will
// end and the buttons will be disabled
TimerTask task = new TimerTask() {
public void run() {
timerSeconds++;
timeLeft = 40 - timerSeconds;
changeText();
if (timerSeconds >= 40) {
showTextEnd();
pause();
gametimer.purge();
gametimer.cancel();
}
}
};
if (isGameRunning == false) {
gametimer.scheduleAtFixedRate(task, 1000, 1000);
isGameRunning = true;
}
正如您所见,计时器将停止,但我无法创建新的计时器。 提前谢谢!
答案 0 :(得分:1)
你必须分配一个新的Timer实例。例如,见下文:
import java.util.Timer;
import java.util.TimerTask;
public class Main {
private static Timer timer;
public static void main(String[] args) throws InterruptedException {
Main main = new Main();
main.launchSomeTimer("john doe");
Thread.sleep(5000);
main.resetSomeTimer();
Thread.sleep(10000);
timer.cancel();
}
private void launchSomeTimer(String name) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("name: " + name);
}
};
timer = new Timer();
timer.schedule(timerTask, 500);
}
public void resetSomeTimer() {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("updating timer");
}
};
timer.cancel();
timer = new Timer();
timer.schedule(timerTask, 1000);
}
}