首先,我对编程有点陌生,所以所有帮助将不胜感激。我得到了这段代码,其中使用了 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;
}
正如你所看到的,计时器将停止,但我无法创建新的计时器。 提前致谢!
最佳答案
您必须分配一个新的计时器实例。例如,见下文:
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);
}
}
关于java - 如何正确重新启动 java.util.Timer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44453825/