Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java SwingWorker.doInBackground() must not access GUI elements

May be this is trivial, I am struggling to understand a simple documentation on SwingWorker.

Here is the copy pasted content

Workflow

There are three threads involved in the life cycle of a SwingWorker :

Current thread: The execute() method is called on this thread. It schedules SwingWorker for the execution on a worker thread and returns immediately. One can wait for the SwingWorker to complete using the get methods.

Worker thread: The doInBackground() method is called on this thread. This is where all background activities should happen. To notify PropertyChangeListeners about bound properties changes use the firePropertyChange and getPropertyChangeSupport() methods. By default there are two bound properties available: state and progress.

Event Dispatch Thread: All Swing related activities occur on this thread. SwingWorker invokes the process and done() methods and notifies any PropertyChangeListeners on this thread.

Often, the Current thread is the Event Dispatch Thread.

--

The worker thread is not the EDT, hence the code in doInBackground() must not access GUI elements. Is my understanding correct?

Background: We have small code that uses SwingWorker but has doInBackground() createing FileChooser and calling setCurrentDirectory(). I suspect that is leading me exception almost same as http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6637181 ( 11-Closed, Not a Defect)

like image 616
Jayan Avatar asked Jan 24 '12 07:01

Jayan


1 Answers

Yes. From a background thread - both regular threads and SwingWorker.doInBackground you must not modify the UI to avoid various trouble.

Instead, wrap the changes in a Runnable and have them executed in the EDT via SwingUtilities.invokeAndWait, SwingUtilities.invokeLater or - when using SwingWorker - via publish (from doInBackground). Within the process method of SwingWorker, which is executed by the EDT, you may access the GUI.

http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html

Personally, I find invokeLater and invokeAndWait easier to use for many situations. SwingWorker is okay for e.g. progress bars.

like image 79
Has QUIT--Anony-Mousse Avatar answered Sep 23 '22 21:09

Has QUIT--Anony-Mousse