I have a problem with a Timer in a chess i’m doing. It’s working “fine”, except it counts seconds two on two (2:00 > 1:58 > 1:56, etc.. but that’s with a 1-second interval, not 2-second interval)
here’ the code where i define, start, and end the timer:
private void setTime(){
totalTime=20;
whiteSec=0;
whiteMin=totalTime;
blackSec=0;
blackMin=totalTime;
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(whiteActive){
if(whiteSec>0) whiteSec-=1;
else{
whiteMin-=1;
whiteSec=60;
}
if(whiteMin==0 && whiteSec==0) endGame();
else GUI.setPlayerTime(whiteMin, whiteSec);
}else{
if(blackSec>0) blackSec-=1;
else{
blackMin-=1;
blackSec=60;
}
if(blackMin==0 && blackSec==0) endGame();
else GUI.setPlayerTime(blackMin, blackSec);
}
}
};
chessTimer = new Timer(1000, taskPerformer);
}
//start
whiteActive = true;
setTime();
wCastling = true;
bCastling = true;
canEnPassant = false;
GUI.setPlayerTime(whiteMin, whiteSec); //this writes the time in some JLabels.
guiRefresh();
activePiece = null;
chessTimer.start();
//end
private void endGame(){
GUI.endGame(checkMate); //shows an endgame JOptionPane
chessTimer.stop();
}
I’d appreciate any help!
While I do not believe a Timer can be started twice, multiple calls to
setTime()would create multiple timers, each of which would independently decrement the fields (until the first is garbage collected, which may or may not happen). If you call the method twice in a row, the two Timer objects would coexist for a while, and it would probably decrement twice per second; callingstop()would stop one of the timers and keep the other around.As a debugging step (and a good practice overall), check that you don’t already have a timer before you create a new one:
To fix it, track down the duplicate call, or band-aid over it by replacing the IllegalStateException with
chessTimer.stop();.