0

In the series of my Boggle questions here's the next.

I need a timer that is customizable by the player. Before a game of Boggle starts, the player can choose a time between 30 and 180 seconds. I tried it with a Timer linked to a TimerTask, this works in the first run of the game but when I go change the seconds in the TimerTask and do another run it says task is busy or has been cancelled. What's the best way to implement a timer that gets reset when a game starts and has a customizable time limit. Can a Timer/ TimerTask be reset?

The code:

class CountDown:

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;
}
}

class 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;
}
}

To reset the timer I try this:

countDown = null;
countDown = new CountDown(displayCountDown);

I get this error when I run it a second time: Exception in thread "main" java.lang.IllegalStateException: Task already scheduled or cancelled

EDIT: what's wrong? Why does this get so much negative reputation? I'm not asking for you guys to just give me a solution, I know you guys hate it and that's not at all what I want... I just want to get back on track, a name of a class would be enough for me... For all clearness: I'm not asking for a finished solution, just for some tips :/

4

1 回答 1

2

“如果计时器的任务执行线程意外终止,例如,因为调用了它的停止方法,那么任何进一步尝试在计时器上安排任务都会导致 IllegalStateException,就像调用了计时器的取消方法一样。”

来自http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html

因此,一种解决方案是在取消第一个计时器后创建一个新计时器。

另一种解决方案是:您可以让一个计时器永远运行,而不是停止和启动计时器,并让所有 DisplayCountDown 实例订阅全局计时器(例如,通过填写一个列表,让计时器遍历列表并通知每个显示倒计时)

于 2013-01-24T22:22:33.227 回答