I'm creating a game that ends if you haven't reached a certain point by the time the timer reaches zero. It currently works and I can create multiple TimerTasks at one time, but I cannot cancel them. Currently, clicking the button resets the timer (on the display) but will still run in the background and end the program when it reaches zero (even though it shouldn't be running). Here's the code for the ActionListener that starts each timer.
public class Game implements Runnable {
private int currentScore, difficulty, level, highscore, x, y;
private boolean playMusic, playClicks, gameRunning;
private boolean stopLastTimer = false;
JFrame gameFrame;
Data data;
JButton target;
Thread t;
JLabel score;
Timer globalTimer = new Timer();
JLabel timer;
ActionListener clickedAction = new ActionListener(){
public void actionPerformed(ActionEvent ae) {
stopLastTimer = true;
t.interrupt();
currentScore++;
score.setText("Score: " + currentScore);
//playClickSound();
globalTimer.schedule(new TimerTask(){
double second = 2.0;
@Override
public void run() {
second = second - 0.1;
if(stopLastTimer) {
this.cancel(); stopLastTimer = false; } //should end old timer here
if(second == 0.0) {
this.cancel();
gameStop();
}
second = limitPrecision(Double.toString(second), 1);
timer.setText(second + "s");
}
},0, 100);
}
};