SwingWorker : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

SwingWorker

SwingWorker makes it easy to set up a background Thread that interacts with the Swing GUI (Graphic User Interface). If the background task does not use the GUI components, it is simpler to use an ordinary Thread instead. SwingWorker formally became part of Swing with  Java version 1.6, but prior to that, you could find the source and incorporate it.

The idea of SwingWorker is to make it easier to follow the two primary rules of Swing Threads.

There are two fundamental things to understand about Swing and threads:

  1. Time-consuming tasks should not be run on the EDT (Event Dispatch Thread) aka Swing thread. Otherwise the application becomes unresponsive. The EDT is busy executing your task and hence can’t process GUI events.
  2. Swing components should be accessed on the EDT only. To access components from other threads, you must use SwingUtilities. invokeAndWait, SwingUtilities. invokeLater or SwingWorker.

The magic under the hood is basically that SwingWorker calls your SwingWorker. process method periodically on the EDT thread, so SwingWorker. process does not have to use SwingUtilities. invokeAndWait or SwingUtilities. invokeLater. Your SwingWorker. doInBackground method runs on a non-EDT thread. It communicates with SwingWorker. process which runs on the EDT thread by calling SwingWorker. publish with packets of data for SwingWorker. process.

You might imagine coding with SwingWorker uses fewer threads than SwingUtilities. invokeLater. However invokeLater uses the Runnable interface, without ever generating any extra threads, just the generation of event, enqueing it, and eventually calling the run method. So unless you are using most of the bells and whistles of SwingWorker, you will probably find it simpler just to spin off a garden variety background Thread and use invokeLater.

SwingWorker runs all your code on the EDT thread. This means you have to be very quick. If you dawdle in the least, your entire GUI will freeze. If you need to do time-consuming tasks, they need to run on some other non-SwingWorker threads.

Like Threads, SwingWorkers objects are not reusable. You must create a new one before you call execute to kick it off.

Learning More

Oracle’s Javadoc on SwingWorker class : available:

This page is posted
on the web at:

http://mindprod.com/jgloss/swingworker.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\swingworker.html
logo
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.
Blog
IP:[65.110.21.43]
Your face IP:[54.211.79.241]
You are visitor number