SwingWorker

Last updated

SwingWorker is a 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. [1]

Contents

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 :

privateDocumentdoc;...JButtonbutton=newJButton("Open XML");button.addActionListener(newActionListener(){@OverridepublicvoidactionPerformed(ActionEvente){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.

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.

Creating the worker

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

SwingWorkerworker=newSwingWorker<Document,Void>(){@OverridepublicDocumentdoInBackground(){DocumentintDoc=loadXML();returnintDoc;}};

Worker execution

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

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 :

privateDocumentdoc;...SwingWorker<Document,Void>worker=newSwingWorker<Document,Void>(){@OverridepublicDocumentdoInBackground(){DocumentintDoc=loadXML();returnintDoc;}@Overridepublicvoiddone(){try{doc=get();}catch(InterruptedExceptionex){ex.printStackTrace();}catch(ExecutionExceptionex){ex.printStackTrace();}}}

Complete Worker example

privateDocumentdoc;...JButtonbutton=newJButton("Open XML");button.addActionListener(newActionListener(){@OverridepublicvoidactionPerformed(ActionEvente){SwingWorker<Document,Void>worker=newSwingWorker<Document,Void>(){@OverridepublicDocumentdoInBackground(){DocumentintDoc=loadXML();returnintDoc;}@Overridepublicvoiddone(){try{doc=get();}catch(InterruptedExceptionex){ex.printStackTrace();}catch(ExecutionExceptionex){ex.printStackTrace();}}};worker.execute();}});

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. [2] The most recent of these versions dates from 2003 and is often referred to as SwingWorker version 3. [3] 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:

SwingWorkerworker=newSwingWorker(){publicObjectconstruct(){...//add the code for the background thread}publicvoidfinished(){...//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 need only 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 is available at http://swingworker.java.net/%5B%5D. Apart from the package name ( org.jdesktop.swingworker ), it is compatible with the Java 6 SwingWorker.

Equivalents

Related Research Articles

In computing, the Java API for XML Processing, or JAXP, one of the Java XML Application programming interfaces, provides the capability of validating and parsing XML documents. It has three basic parsing interfaces:

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

<span class="mw-page-title-main">Swing (Java)</span> Java-based GUI toolkit

Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.

<span class="mw-page-title-main">ActionScript</span> Object-oriented programming language created for the Flash multimedia platform

ActionScript is an object-oriented programming language originally developed by Macromedia Inc.. It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript, though it originally arose as a sibling, both being influenced by HyperTalk. ActionScript code is usually converted to byte-code format by a compiler.

In computer programming, a callback or callback function is any reference to executable code that is passed as an argument to another piece of code; that code is expected to call back (execute) the callback function as part of its job. This execution may be immediate as in a synchronous callback, or it might happen at a later point in time as in an asynchronous callback. They are also called blocking and non-blocking.

This article compares two programming languages: C# with Java. While the focus of this article is mainly the languages and their features, such a comparison will necessarily also consider some features of platforms and libraries. For a more detailed comparison of the platforms, see Comparison of the Java and .NET platforms.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

Javadoc is a documentation generator created by Sun Microsystems for the Java language for generating API documentation in HTML format from Java source code. The HTML format is used for adding the convenience of being able to hyperlink related documents together.

The event dispatching thread (EDT) is a background thread used in Java to process events from the Abstract Window Toolkit (AWT) graphical user interface event queue. It is an example of the generic concept of event-driven programming, that is popular in many other contexts than Java, for example, web browsers, or web servers.

In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and Java packages may be annotated. Like Javadoc tags, Java annotations can be read from source files. Unlike Javadoc tags, Java annotations can also be embedded in and read from Java class files generated by the Java compiler. This allows annotations to be retained by the Java virtual machine at run-time and read via reflection. It is possible to create meta-annotations out of the existing ones in Java.

The active object design pattern decouples method execution from method invocation for objects that each reside in their own thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.

Layout managers are software components used in widget toolkits which have the ability to lay out graphical control elements by their relative positions without using distance units. It is often more natural to define component layouts in this manner than to define their position in pixels or common distance units, so a number of popular widget toolkits include this ability by default. Widget toolkits that provide this function can generally be classified into two groups:

In programming and software design, an event is an action or occurrence recognized by software, often originating asynchronously from the external environment, that may be handled by the software. Computer events can be generated or triggered by the system, by the user, or in other ways. Typically, events are handled synchronously with the program flow; that is, the software may have one or more dedicated places where events are handled, frequently an event loop.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

synth is a skinnable Java look and feel, which is configured with an XML property file.

In computer science, marshalling or marshaling is the process of transforming the memory representation of an object into a data format suitable for storage or transmission, especially between different runtimes. It is typically used when data must be moved between different parts of a computer program or from one program to another.

<span class="mw-page-title-main">Abstract Window Toolkit</span> Java-based GUI toolkit

The Abstract Window Toolkit (AWT) is Java's original platform-dependent windowing, graphics, and user-interface widget toolkit, preceding Swing. The AWT is part of the Java Foundation Classes (JFC) — the standard API for providing a graphical user interface (GUI) for a Java program. AWT is also the GUI toolkit for a number of Java ME profiles. For example, Connected Device Configuration profiles require Java runtimes on mobile telephones to support the Abstract Window Toolkit.

In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function. It is semantically related to the concept of a coroutine and is often implemented using similar techniques, and is primarily intended to provide opportunities for the program to execute other code while waiting for a long-running, asynchronous task to complete, usually represented by promises or similar data structures. The feature is found in C#, C++, Python, F#, Hack, Julia, Dart, Kotlin, Rust, Nim, JavaScript, Swift and Zig.

References

  1. SwingWorker
  2. See the javax.swing package-summary before and after J2SE 6.0. Also notice that there is no SwingWorker class listed in the index pages of the documentation, until version 6.0: , .
  3. You can download it "SwingWorker 3". Internet Archive. Archived from the original on June 26, 2012.