views:

284

answers:

3

I know that this problem is caused by the sleep or wait calling on the main thread and that the answer on how to solve this will be to put the method into a seperate thread and then make that thread sleep. But the code is a mess and don't really have the time to sort it out and split it up into separate threads and was wondering if there is any other way of doing this? Even if it is not the cleanest or most common practice for working with GUIs. I only need about a seconds pause from the method.

+1  A: 

It is not possible to sleep on an event thread and not cause a GUI freeze. However in Swing, the event thread is created and managed behind the scenes - you main thread (the one originating from main() method) is not the event thread.

So, you can safely sleep on your main thread.

pajton
+5  A: 

You can't do it without creating a separate thread. Creating a thread in Java is easy. The only thing to pay attention to is that you can only touch the UI through the main thread. For this reason you need to use something like SwingUtilities.invokeLater().

kgiannakakis
Or, if he needs to go the other way, he could use a javax.swing.SwingWorker to move the method off the Event Dispatch Thread (EDT).
ILMTitan
Thanks, I assumed this was going to be the answer but thought I would put it to the experts anyway and see if there was a work around available.
pie154
A: 

Using a separate thread for the code is your only solution. Every action started by the Swing thread must be delegated to a separate thread if it would otherwise block the GUI.

Daniel Bleisteiner