Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until a SwingWorker is complete?

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.

like image 441
Karlovsky120 Avatar asked Feb 13 '13 03:02

Karlovsky120


1 Answers

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

like image 117
MadProgrammer Avatar answered Sep 30 '22 02:09

MadProgrammer