SwingWorker

From Wikipedia, the free encyclopedia

Jump to: navigation, search

SwingWorker is a popular utility class developed by Sun Microsystems for the Swing library of the Java programming language. SwingWorker enables proper use of the event dispatching thread. As of Java 6, 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.

Contents

[edit] Usage in Java 6.0

[edit] 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.

[edit] SwingWorker 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.

[edit] Creating the worker

The following code defines the SwingWorker, which encapsulate the loadXML() method call :

 SwingWorker worker = new SwingWorker<Document, Void>() {
    public Document doInBackground() {
        Document intDoc = loadXML();
        return intDoc;
    }
 };

[edit] Worker execution

Execution is started by using the SwingWorker.execute() method.

[edit] Retrieving the result

The result can be retrieved by using the SwingWorker.get() method.

As calling 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 :

 private Document doc;
 ...
 SwingWorker worker = new SwingWorker<Document, Void>() {
    public Document doInBackground() {
        Document intDoc = loadXML();
        return intDoc;
    }
    public void done() {
       doc = get();
    }
 };

[edit] Complete Worker example

  private Document doc;
  ...
  JButton button = new JButton("Open XML");
  button.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       SwingWorker<Document, Void> worker = 
          new SwingWorker<Document, Void>() {
 
          public Document doInBackground() {
            Document intDoc = loadXML();
            return intDoc;
          }
          public void done() {
            doc = get();
          }
       };
       worker.execute();
     }
  });

[edit] 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 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.

[edit] 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.

[edit] See also

[edit] External links

[edit] Outdated tutorials

Personal tools
Languages