Stop a stopwatch

You can either cancel the entire Timer by calling Timer.cancel(), or you can cancel individual tasks by calling TimerTask.cancel().

Either way, you’ll need to keep a reference to the timer and/or task instance when you create it, so that your stop routine can call the appropriate cancel method.

Update:

So you effectively want to be able to pause the timer? I don’t think this is supported by the standard interface in java.util.Timer. You could do this by adding a pause() method (or similar) to your custom task, recording the elapsed time up to that point, and restarting the counting when the start button is clicked again. Note that using this technique, you wouldn’t stop the timer task itself until you’re finished with it completely. It still runs in the background, but you only do anything with it when the stopwatch has been started and is “running” (ie. some kind of flag to indicate the stopwatch’s state).

A couple of notes:

  • java.util.Timer runs on a non-EDT thread, so if you’re interacting with member variables in both the timer and in Swing action events, you’ll need to appropriately handle the implications of multiple threads. It might be worth investigating javax.swing.Timer, which will fire events on the EDT.

  • Also, if you want a super-duper accurate stopwatch, you might consider using System.nanoTime() rather than currentTimeMillis().

Leave a Comment