I have a SwingWorker, which does some computations in the background (these actions are situated in the overridden doInBackground()
method). So, I also use the execute()
method to begin the computations. How I can get the result of these computations when they are finished?
Asked
Active
Viewed 7,294 times
3

Unai Vivi
- 3,073
- 3
- 30
- 46

Dmitry Belaventsev
- 6,347
- 12
- 52
- 75
-
It's no code now. Now I think about how to connect SwingWorker and my model and view of MVC-structure of application – Dmitry Belaventsev Dec 24 '11 at 17:02
2 Answers
4
-
I need exactly return statement. What will happened, if I just call doInBackground method of my worker? – Dmitry Belaventsev Dec 24 '11 at 17:00
-
2It'll just run, possibly blocking the EDT. Instead, instantiate the worker and `execute()` it, as shown in the examples. – trashgod Dec 24 '11 at 17:08
-
@dizpers _What will happened, I just call doInBackground_ hell breaking loose ;-) As always when you do something **terribly wrong** - simply stick to the usage as extensively explained in both the java doc and the tutorial chapter on concurrency in Swing – kleopatra Dec 25 '11 at 12:32
4
Override the done
method - that method will be called when the work is complete. Oracle has a comprehensive tutorial here: Improve Application Performance With SwingWorker in Java SE 6
Also see another SO question: How do I use SwingWorker in Java?
You can call get
to retrieve the results but if the worker isn't done the thread will block until the worker is done. That means if you call get
from the Event Dispatch Thread (EDT) your GUI will be unresponsive if the worker isn't done. You can call isDone
to determine if the worker has completed.
Finally, you can attach a property change listener to be notified of the worker's progress, including when it completes its task. The first link I posted gives an example of that.
-
thx! I will try it! mayby there are some common patterns of using SwingWorker in MVC? – Dmitry Belaventsev Dec 24 '11 at 17:10
-
1@dizpers, yes - the Swing Worker and the work it can be decoupled from the UI. Attach a listener to the worker and update the UI when the worker is complete. You can also fire a `PropertyChangeEvent` to recognize intermediate progress, if you want your UI to keep the user apprised of progress. – Paul Dec 24 '11 at 17:17
-
-
1@jj_, `get()` is a `SwingWorker` method and as such is documented in the API. Here's the link to the method in the Java 8 API: https://docs.oracle.com/javase/8/docs/api/javax/swing/SwingWorker.html#get-- – Paul Mar 30 '15 at 18:06