SwingWorker

SwingWorker

SwingWorker is a popular utility class developed by Sun Microsystems for the Swing library of the Java programming language. Javadoc:SE|javax/swing|SwingWorker enables proper use of the event dispatching thread. As of Java 6, Javadoc:SE|javax/swing|SwingWorker is included in the JRE.

Several incompatible, unofficial, versions of SwingWorker were produced from 1998 to 2006, and care must be taken to avoid the abundant documentation on these versions predating Java 6.

Usage in Java 6.0

The event dispatching thread problem

SwingWorker is useful when a time-consuming task has to be performed following a user-interaction event (for example, parsing a huge XML File, on pressing a JButton). The most straightforward way to do it is : private Document doc; ... JButton button = new JButton("Open XML"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doc = loadXML(); } });This will work, but unfortunately, the loadXML() method will be called in the same thread as the main Swing thread (the Event dispatching thread), so if the method needs time to perform, the GUI will freeze during this time.

wingWorker solution

This problem is not specific to Java, but common to many GUI models. SwingWorker proposes a way to solve it by performing the time-consuming task on another background thread, keeping the GUI responsive during this time.

Creating the worker

The following code defines the SwingWorker, which encapsulate the loadXML() method call : SwingWorker worker = new SwingWorker() { public Document doInBackground() { Document intDoc = loadXML(); return intDoc; } };

Worker execution

Execution is started by using the Javadoc:SE|name=SwingWorker.execute()|javax/swing|SwingWorker|execute() method.

Retrieving the result

The result can be retrieved by using the Javadoc:SE|name=SwingWorker.get()|javax/swing|SwingWorker|get() method.

As calling Javadoc:SE|name=get()|javax/swing|SwingWorker|get() on the Event Dispatch Thread blocks all events, including repaints, from being processed until the task completes, one must avoid calling it before the lengthy operation has finished. There are two ways to retrieve the result after the task completion :
* override the Javadoc:SE|name=SwingWorker.done()|javax/swing|SwingWorker|done() method. This method is called on the main event dispatching thread. private Document doc; ... SwingWorker worker = new SwingWorker() { public Document doInBackground() { Document intDoc = loadXML(); return intDoc; } public void done() { doc = get(); } };
* register a listener by using the worker Javadoc:SE|name=SwingWorker.addPropertyChangeListener(PropertyChangeListener) |javax/swing|SwingWorker|addPropertyChangeListener(java.beans.PropertyChangeListener) method. The listener will be notified of changes in the worker state.

Complete Worker example

private Document doc; ... JButton button = new JButton("Open XML"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingWorker worker = new SwingWorker() {

public Document doInBackground() { Document intDoc = loadXML(); return intDoc; } public void done() { doc = get(); } }; worker.execute(); } });

Usage before Java 6.0

SwingWorker has only been part of JSE since Java 6.0. Sun has released versions to be used with earlier JDKs however. The most recent of these versions dates from 2003 and is often referred to as SwingWorker version 3. You can download it [http://java.sun.com/products/jfc/tsc/articles/threads/src/SwingWorker.java here] . Unfortunately, the JDK 6.0 SwingWorker and the Version 3 SwingWorker use different method names and are not compatible. The backport version (see below) is now recommended for pre-Java 6 usage.

An example for instantiating SwingWorker 3 is shown below:

SwingWorker worker = new SwingWorker() { public Object construct() { ... //add the code for the background thread } public void finished() { ... //code that you add here will run in the UI thread }

}; worker.start(); //Start the background thread

The start() method executes the code added in the construct() method in a separate thread. To be alerted when the background thread finishes, one only needs to override the finished() method. The construct() method can return a result which can later be retrieved using SwingWorker's get() method.

Backport of the Java 6 SwingWorker

A backport of the Java 6 SwingWorker to Java 5 has been available at https://swingworker.dev.java.net/ since March 2007. Apart from the package name ( org.jdesktop.swingworker ), it is compatible with the Java 6 SwingWorker.

ee also

*Swing (Java)
*Event dispatching thread
*BackgroundWorker, the equivalent .NET Framework class

External links

* [http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html SwingWorker Javadoc] from Java 6.
* [http://www.javaswing.net/using-swingworker-a-step-by-step-tutorial.html Using SwingWorker - A Step by Step tutorial] , " from JavaSwing.net
* [http://java.sun.com/docs/books/tutorial/uiswing/concurrency/worker.html Worker Threads and SwingWorker] from Sun's Java 6 [http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html Concurrency in Swing] tutorial.
* [http://java.sun.com/developer/technicalArticles/javase/swingworker/ Improve Application Performance With SwingWorker in Java SE 6] by John O'Conner, January 2007.
*https://swingworker.dev.java.net/ the official page of the developer team.
* [http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html Using a Swing Worker Thread New Ways to Perform Background Tasks] , from Sun.

Outdated tutorials

* [http://www.javaworld.com/javaworld/jw-06-2003/jw-0606-swingworker.html Customize SwingWorker to improve Swing GUIs] article on [http://www.javaworld.com JavaWorld] [Note: this refers to an earlier, somewhat incompatible, non-library version of SwingWorker from 2003. Needs to be replaced with better reference.]
* [http://www.swingwiki.org/best:use_worker_thread_for_long_operations Tutorial on SwingWorker Thread usage] from [http://www.swingwiki.org SwingWiki.org] [Note: Outdated as above.]


Wikimedia Foundation. 2010.

Игры ⚽ Поможем сделать НИР

Look at other dictionaries:

  • Event dispatching thread — The event dispatching thread (EDT) is a background thread used in Java to process events from the Abstract Windowing Toolkit (AWT) graphical user interface event queue. These events are primarily update events that cause user interface components …   Wikipedia

  • Abstract Window Toolkit — The Abstract Window Toolkit (AWT) is Java s original platform independent windowing, graphics, and user interface widget toolkit. The AWT is now part of the Java Foundation Classes (JFC) mdash; the standard API for providing a graphical user… …   Wikipedia

  • Swing (Java) — Die Widgets von Swing mit dem Ocean Look and Feel (Standard seit Java 1.5) …   Deutsch Wikipedia

  • Abstract Window Toolkit — Для улучшения этой статьи желательно?: Исправить статью согласно стилистическим правилам Википедии …   Википедия

  • Windows Forms — Some after market and third party libraries have been created to address this issue. The most widely used of these is the [http://www.microsoft.com/downloads/details.aspx?familyid=98C6CC9D 88E1 4490 8BD6 78092A0F084E displaylang=en| User… …   Wikipedia

  • Java version history — The Java language has undergone several changes since JDK 1.0 as well as numerous additions of classes and packages to the standard library. Since J2SE 1.4, the evolution of the Java language has been governed by the Java Community Process (JCP) …   Wikipedia

  • SwingLabs — Infobox Software name = swingLabs logo= caption = developer = Sun latest release version = latest release date = operating system = Cross platform genre = Widget library license = LGPL website = [https://swinglabs.dev.java.net/ swinglabs.dev.java …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”