3

How could I create a timer that is compatible in a JFrane/JPanel oriented program where it just waits 1 second, and then continues on with the rest of the code?

I do not want to use Thread.sleep(); since it is causing problems for me.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Do you actually want to delay the GUI-Thread (meaning your GUI will freeze for the delay) or just one single event? For the latter (which is probably what you want), @Puce's answer seems to do the job. – Turing85 Jun 19 '15 at 15:05

2 Answers2

4

For this kind of tasks you can use javax.swing.Timer. It integrates with the Event Dispatching Thread (EDT).

Puce
  • 37,247
  • 13
  • 80
  • 152
-1
TimeUnit.SECONDS.sleep(1)

More helpful information here: How to delay in Java?

Community
  • 1
  • 1
jknam
  • 93
  • 7
  • That linked question is about an app. with no GUI. Apps. with GUIs require special consideration (see the answer of @Puce for how to do it). The OP even *mentions* having problems using `sleep()` .. – Andrew Thompson Jun 19 '15 at 14:19
  • I'm fairly certain it doesn't matter if there is a GUI or not. Plenty of examples of GUIs using TimeUnit to delay their app. One google search returned plenty of examples. And I didn't realize TimeUnit.sleep() was just overhead for Thread.sleep(). My mistake. – jknam Jun 19 '15 at 14:24
  • http://stackoverflow.com/questions/26834078/how-to-initialize-gui-objects-in-a-thread-safe-manner-in-java-swing – jknam Jun 19 '15 at 14:27
  • @jknam all three of your examples already use multithreading. This is a huge difference. I think Andrew Thompson spoke of examples, in which the GUI-Thread is being paused (which causes the GUI to be unresponsive). – Turing85 Jun 19 '15 at 15:08