I have the following timer:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
intCounter.incrementCount();
System.out.println(intCounter.counterNum);
};
};
It runs when the start button is pressed and should stop when the pause button is pressed however it will not stop. Here is the code for my pause button, the text "pressed pause" prints however the timer continues to count.
if (e.getSource() == pauseButton) {
System.out.println("pressed pause");
task.cancel();
timer.cancel();
EDIT: I have tried modifying my code with an answer posted for a similar question but the result did not change. I changed my TimerTask to look like this:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
private volatile Thread thread;
public void run() {
thread = Thread.currentThread();
intCounter.incrementCount();
System.out.println(intCounter.counterNum);
}
public boolean cancel() {
Thread thread = this.thread;
if (thread != null) {
thread.interrupt();
}
return super.cancel();
}
};
This is what your task should look like: