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.
private Document doc;
...
JButton button = new JButton("Open XML");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doc = loadXML();} });
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 proposes a way to solve it by performing the time-consuming task on another background thread, keeping the GUI responsive during this time.
loadXML() method call :
SwingWorker worker = new SwingWorker() {
public Document doInBackground() {
Document intDoc = loadXML();
return intDoc;}
};
As calling 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
public Document doInBackground() {
Document intDoc = loadXML();
return intDoc;
}
public void done() {
doc = get();
}
};
private Document doc;
...
JButton button = new JButton("Open XML");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingWorkerworker =
new SwingWorker() {
public Document doInBackground() {
Document intDoc = loadXML();
return intDoc;}
public void done() {
doc = get();} };
worker.execute();} });
An example for instantiating SwingWorker 3 is shown below:
};
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.
org.jdesktop.swingworker ), it is compatible with the Java 6 SwingWorker.