Java SwingWorker.doInBackground () must not have access to GUI elements

Maybe this is trivial, I'm struggling to understand simple SwingWorker documentation.

Here is the copied text

The working process

There are three threads involved in the SwingWorker life cycle:

Current thread: The execute () method is called on this thread. This is a SwingWorker schedule to run on the workflow and returns immediately. You can expect SwingWorker to finish using get methods.

Workflow: in this thread, the doInBackground () method is called. This is where all background actions should happen. To notify PropertyChangeListeners of related property changes, use the firePropertyChange and getPropertyChangeSupport () methods. By default, there are two related properties: state and progress.

Dispatch Thread event: all Swing-related actions occur on this thread. SwingWorker calls the process and done () methods and notifies PropertyChangeListeners about this.

Often the current thread is Thread Dispatch Thread.

-

The workflow is not an EDT, so the code in doInBackground () should not have access to the GUI elements. Do I understand correctly?

Background: We have a little code that uses SwingWorker but has doInBackground () that creates a FileChooser and calls setCurrentDirectory() . I suspect this excludes me in much the same way as http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6637181 (11-closed, not defect)

+7
source share
1 answer

Yes. From the background thread - both regular threads and SwingWorker.doInBackground you should not change the user interface to avoid various problems.

Instead, wrap the changes in Runnable and execute them in EDT using SwingUtilities.invokeAndWait , SwingUtilities.invokeLater or — when using SwingWorker — through publish (from doInBackground ). As part of the process SwingWorker method that EDT runs, you can access the graphical interface.

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

Personally, I find invokeLater and invokeAndWait easier to use for many situations. SwingWorker is fine, for example. progress indicators.

+11
source

All Articles