Question

With Java Swing, is it possible to pause the current thread Runnable and give room to the Event Dispatching Thread to update the gui?

I know it is possible with multi-threading (SwingWorker class) but I was wondering if there's an easier way to achieve this for single threaded programs (aka: all my code is in the gui's Run()).

E.g. Matlab has the very convenient drawnow; method

If not: how can I split the updating task to a second thread without having to rewrite anything? Would that be the Updating the gui from a running thread from this link?

Was it helpful?

Solution

The short answer is no. If you pause the current thread (which according to you is the EDT) then you pause the EDT...

You can make requests that the UI be updated using methods like repaint, but this also assumes you are not blocking the EDT with things like loops and pauses, as the EDT will need time to process these requests.

And no, I wouldn't follow the link's advice, as it violates the single thread of Swing by updating the components outside of the of EDT

Depending on your needs you would either need to use a javax.swing.Timer or SwingWorker. Yes, you can use a Thread, you become responsible for ensuring that all updates to the UI are synced back to the EDT, which the other two suggest provide mechanisms for.

Take a look at Concurrency in Swing for more details

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top