I want my program to start off using a countdown timer that will be displayed to the user. The only way I can think to do that is to label.setText() and Thread.sleep(). I've tried for about 20min trying to get it to work, but can't seem to crack it. Help?
Asked
Active
Viewed 3,216 times
2 Answers
1
Use a Swing timer. Basically you create a class that implements ActionListener
, create a javax.swing.Timer
, and the actionPerformed
method of the ActionListener
gets called at an interval you specify. In your actionPerformed
method, check the time, and update the value to be displayed when appropropriate, and call repaint()
. Use an interval of 0.1 second, and your countdown will be smooth and accurate enough.

Ernest Friedman-Hill
- 80,601
- 10
- 150
- 186
-
+1 for `javax.swing.Timer`; there's a related count-up example [here](http://stackoverflow.com/a/2576909/230513). – trashgod Jan 04 '12 at 12:56
-
Thanks a bunch for this man! Got it working. It's actually part of a project for my matric IT PAT. – John Smith Jan 04 '12 at 15:34
1
I wouldn't count on the accuracy of Thread.sleep
, but:
for(int i = 20; i >= 0; i--) {
label.setText(i + " seconds remaining");
Thread.sleep(1000);
}
This will, of course, block the UI thread while sleeping, so you probably need to run it on a separate thread. This means you will need something like SwingUtilities.InvokeLater
to update the UI, since you are using a thread different than the UI one:
for(int i = 20; i >= 0; i--) {
SwingUtilities.InvokeLater(new Runnable() {
public void run() {
label.setText(i + " seconds remaining");
}
});
Thread.sleep(1000);
}

Tudor
- 61,523
- 12
- 102
- 142
-
Not this. You shouldn't call any Swing methods except on the event thread, and you can't sleep on the event thread since the screen will then not repaint; so this can never be the right solution. Animation always must involve a second thread. – Ernest Friedman-Hill Jan 04 '12 at 12:30
-
@ErnestFriedman-Hill: And what am I doing in the above code? You probably posted while I was adding the explanation and the second code snippet. – Tudor Jan 04 '12 at 12:30
-