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 :/