Hubbry Logo
search
logo

SwingWorker

logo
Community Hub0 Subscribers
Write something...
Be the first to start a discussion here.
Be the first to start a discussion here.
See all
SwingWorker

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.

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.

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 :

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.

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.

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

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

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

See all
User Avatar
No comments yet.