Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
SwingWorker
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Utility class for Java}} {{multiple issues| {{primary sources|date=June 2012}} {{more citations needed|date=June 2012}} {{Howto|date=April 2011}} }} '''SwingWorker''' is a [[utility class]] developed by [[Sun Microsystems]] for the [[Swing (Java)|Swing]] library of the [[Java (programming language)|Java programming language]]. SwingWorker enables proper use of the [[event dispatching thread]]. As of [[Java 6]], SwingWorker is included in the [[Java Runtime Environment|JRE]].<ref>{{Javadoc:SE|javax/swing|SwingWorker|module=java.desktop}}</ref> 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 : <syntaxhighlight lang="java"> private Document doc; ... JButton button = new JButton("Open XML"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { doc = loadXML(); } }); </syntaxhighlight> This will work, but unfortunately, the <code>loadXML()</code> method will be called in the same [[Thread (computer science)|thread]] as the main Swing thread (the [[Event dispatching thread]]), so if the method needs time to perform, the [[Graphical user interface|GUI]] will freeze during this time. ===SwingWorker solution=== This problem is not specific to Java, but common to many [[Graphical user interface|GUI]] models. <code>SwingWorker</code> proposes a way to solve it by performing the time-consuming task on another background thread, keeping the [[Graphical user interface|GUI]] responsive during this time. ====Creating the worker==== The following code defines the SwingWorker, which encapsulates the <code>loadXML()</code> method call : <syntaxhighlight lang="java"> SwingWorker worker = new SwingWorker<Document, Void>() { @Override public Document doInBackground() { Document intDoc = loadXML(); return intDoc; } }; </syntaxhighlight> ====Worker execution==== Execution is started by using the '''{{Javadoc:SE|name=SwingWorker.execute()|javax/swing|SwingWorker|execute()|module=java.desktop}}''' method. ====Retrieving the result==== The result can be retrieved by using the '''{{Javadoc:SE|name=SwingWorker.get()|javax/swing|SwingWorker|get()|module=java.desktop}}''' method. As calling '''{{Javadoc:SE|name=get()|javax/swing|SwingWorker|get()|module=java.desktop}}''' 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()|module=java.desktop}}''' method. This method is called on the main [[event dispatching thread]]. <syntaxhighlight lang="java"> private Document doc; ... SwingWorker<Document, Void> worker = new SwingWorker<Document, Void>() { @Override public Document doInBackground() { Document intDoc = loadXML(); return intDoc; } @Override public void done() { try { doc = get(); } catch (InterruptedException ex) { ex.printStackTrace(); } catch (ExecutionException ex) { ex.printStackTrace(); } } } </syntaxhighlight> * register a listener by using the worker '''{{Javadoc:SE|name=SwingWorker.addPropertyChangeListener(PropertyChangeListener) |javax/swing|SwingWorker|addPropertyChangeListener(java.beans.PropertyChangeListener)|module=java.desktop}}''' method. The listener will be notified of changes in the worker state. ====Complete Worker example==== <syntaxhighlight lang="java"> private Document doc; ... JButton button = new JButton("Open XML"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SwingWorker<Document, Void> worker = new SwingWorker<Document, Void>() { @Override public Document doInBackground() { Document intDoc = loadXML(); return intDoc; } @Override public void done() { try { doc = get(); } catch (InterruptedException ex) { ex.printStackTrace(); } catch (ExecutionException ex) { ex.printStackTrace(); } } }; worker.execute(); } }); </syntaxhighlight> ==History: Usage before Java 6.0== SwingWorker has been part of Java SE only since Java 6.0. Sun has released versions to be used with earlier JDKs, although they were unofficial versions which were not part of the Java SE and were not mentioned in the standard library documentation.<ref>See the <code>javax.swing</code> package-summary [http://download.oracle.com/javase/1.5.0/docs/api/javax/swing/package-summary.html before] and [http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html after] J2SE 6.0. Also notice that there is no SwingWorker class listed in the index pages of the documentation, until version 6.0: [http://download.oracle.com/javase/1.5.0/docs/api/index-files/index-19.html], [http://download.oracle.com/javase/6/docs/api/index-files/index-19.html].</ref> The most recent of these versions dates from 2003 and is often referred to as SwingWorker version 3.<ref name="Wayback_access">You can download it {{cite web | url=http://faq.web.archive.org/page-without-wayback-code/ | title=SwingWorker 3 | last= | first= | publisher=Internet Archive | date= | url-status=dead | archive-url=https://web.archive.org/web/20120626141303/http://java.sun.com/products/jfc/tsc/articles/threads/src/SwingWorker.java | archive-date=June 26, 2012 }}</ref> 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: <syntaxhighlight lang="java"> 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 </syntaxhighlight> The <code>start()</code> method executes the code added in the construct() method in a separate thread. To be alerted when the background thread finishes, one need only override the <code>finished()</code> method. The <code>construct()</code> method can return a result which can later be retrieved using SwingWorker's <code>get()</code> method. ===Backport of the Java 6 SwingWorker=== A backport of the Java 6 SwingWorker to Java 5 is available at http://swingworker.java.net/{{Dead link|date=June 2018 |bot=InternetArchiveBot |fix-attempted=no }}. Apart from the package name ( <code>org.jdesktop.swingworker</code> ), it is compatible with the Java 6 SwingWorker. ==Equivalents== * <code>System.ComponentModel.BackgroundWorker</code> - [[.NET Framework]] * <code>flash.system.Worker</code> - [[Adobe Flash]] * <code>android.os.AsyncTask</code> - [[Android (operating system)|Android]] == References == <references/> ==External links== {{Portal|Computer programming}} * [http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html SwingWorker] class documentation for Java 7. * [http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html Worker Threads and SwingWorker] from Oracle's Java [http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html Concurrency in Swing] tutorial. * [http://www.oracle.com/technetwork/articles/javase/swingworker-137249.html Improve Application Performance With SwingWorker in Java SE 6] by John O'Conner, January 2007. {{Java desktop}} {{DEFAULTSORT:Swingworker}} [[Category:JDK components]] [[Category:Articles with example Java code]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite web
(
edit
)
Template:Dead link
(
edit
)
Template:Java desktop
(
edit
)
Template:Javadoc:SE
(
edit
)
Template:Multiple issues
(
edit
)
Template:Portal
(
edit
)
Template:Short description
(
edit
)