Search code examples
javatimerthread-sleep

Pause a simple timer


In Java how would I pause a simple timer?

This may be a bit of newbie question - I'm new to a lot of this. I have a simple pomodoro timer using Thread.sleep( MILLISECONDS ) , which runs repeatedly in a for loop, and then chimes using the default system sound (Toolkit.getDefaultToolkit().beep(); ) .

I'd like to put a JButton to pause it( I'm using a simple JPanel that shows the pomodoros completed, and at what time.), then show some periods like so ...... on the JPanel

What is the best way to pause/resume? Thanks!


Solution

  • Don't call Thread.sleep. This will block the EDT if done on the UI Thread. Instead use a Swing Timer and set the delay to the period interval. pause/resume functionality can be achieved using stop/start respectively.