How to wait until a SwingWorker is complete?

Karlovsky120 picture Karlovsky120 · Feb 13, 2013 · Viewed 6.9k times · Source

I have a swing worker that computes in the background, while updating a progressBar in a JFrame.

How can I make my main thread wait for the doInBackground () to finish?

I know I can put things in done() method, but I was wondering if there was a way to actually make the program wait (that thread, to be correct).

Something similar to what a modal JDialog would do.

So...

SwingWorker a = new SwingWorker();
a.execute

doOtherStuff();

doOtherStuff is ran only after doInBackground is complete, but without putting the said method in the done() method of the SwingWorker.

Answer

MadProgrammer picture MadProgrammer · Feb 13, 2013

The short answer is, yes.

SwingWorker#get will block until the doInBackground method returns.

The long answer is, probably not what you want to do.

If you launch the SwingWorker from the EDT and the call SwingWorker#get you will be block the EDT, preventing it from processing any updates which leads you back to the reason why you're using SwingWorker.

In this case, you have two choices. You could provide SwingWorker with a callback interface, which it would be able to call from done once the SwingWorker has completed. Or you could attach a PropertyChangeListener to the SwingWorker and monitor the state value, waiting until it equals StateValue.Done