When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads. Each task running on a worker thread is represented by an instance ofjavax.swing.SwingWorker.SwingWorkeritself is an abstract class; you must define a subclass in order to create aSwingWorkerobject; anonymous inner classes are often useful for creating very simpleSwingWorkerobjects.
SwingWorkerprovides a number of communication and control features:These features are discussed in the following subsections.
- The
SwingWorkersubclass can define a method,done, which is automatically invoked on the event dispatch thread when the background task is finished.SwingWorkerimplementsjava.util.concurrent.Future. This interface allows the background task to provide a return value to the other thread. Other methods in this interface allow cancellation of the background task and discovering whether the background task has finished or been cancelled.- The background task can provide intermediate results by invoking
SwingWorker.publish, causingSwingWorker.processto be invoked from the event dispatch thread.- The background task can define bound properties. Changes to these properties trigger events, causing event-handling methods to be invoked on the event dispatch thread.
Note: Thejavax.swing.SwingWorkerclass was added to the Java platform in Java SE 6. Prior to this, another class, also calledSwingWorker, was widely used for some of the same purposes. The oldSwingWorkerwas not part of the Java platform specification, and was not provided as part of the JDK.The new
javax.swing.SwingWorkeris a completly new class. Its functionality is not a strict superset of the oldSwingWorker. Methods in the two classes that have the same function do not have the same names. Also, instances of the oldSwingWorkerclass were reusable, while a new instance ofjavax.swing.SwingWorkeris needed for each new background task.Throughout the Java Tutorials, any mention of
SwingWorkernow refers tojavax.swing.SwingWorker.