Java SwingWorker

The following is the full source-code for an application demonstrating the use of javax.swing.SwingWorker in Java 6. The application is very trivial and consists of a text area and two buttons: Start and Stop. When the user clicks on the Start button, the text area begins to count seconds by printing each second on a new line. This continues indefinitely until the user clicks the Stop button.

A SwingWorker is required to separate the grunt logic (in this case the infinite loop with the one-second sleep interval) from the UI logic (printing the counter in the text area and processing the user Stop button click).

The code below demonstrates the use of SwingWorker and the doInBackground(), publish(), process() and done() methods. There are other ways to achieve this same result, and the SwingWorker has additional methods that are not used here, such as the timeout enabled get() method and the progress() methods. These can come very handy in different scenarios, so please refer to the API and be familiar with the functionality for when you need it.

package gluga.com.swingworker;

import java.util.Iterator;
import java.util.List;
import javax.swing.SwingWorker;
import javax.swing.UIManager;

public class SwingWorkerDemo extends javax.swing.JFrame {

/** Creates new form SwingWorkerDemo */
public SwingWorkerDemo() {
initComponents();
}

@SuppressWarnings("unchecked")
//
private void initComponents() {

startButton = new javax.swing.JButton();
stopButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
textArea = new javax.swing.JTextArea();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("SwingWorkerDemo");
getContentPane().setLayout(null);

startButton.setText("Start");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
getContentPane().add(startButton);
startButton.setBounds(39, 92, 57, 23);

stopButton.setText("Stop");
stopButton.setEnabled(false);
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(evt);
}
});
getContentPane().add(stopButton);
stopButton.setBounds(96, 92, 55, 23);

textArea.setColumns(20);
textArea.setRows(5);
jScrollPane1.setViewportView(textArea);

getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(14, -1, 162, 92);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-202)/2, (screenSize.height-149)/2, 202, 149);
}//

private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
//define a local class that extends SwingWorker
class Worker extends SwingWorker {

@Override
protected Object doInBackground() {
//this method is executed in a background thread when you invoke execute on the Worker object
int counter = 0;
while (!isCancelled()) { //run infinitelly until the SwingWorker receives the cancel signal

publish("" + ++counter); //publish an update, this will get added to a list and processed in bulk by the process() method at some point

try {
Thread.sleep(1000); //sleep for one second

} catch (InterruptedException e) {
break; //break if cancelled during a sleep (interrupted)

}
}
return "Stopped."; //the get() method will return this

}

@Override
protected void process(List chunks) { //this will process a list of objects from the publish() method
//this method is executed on the Event Dispatcher thread

Iterator it = chunks.iterator();
while (it.hasNext()) { //publish() operations are buffered to a list and proccessed in chunks

textArea.append((String) it.next() + "\n");
textArea.setCaretPosition(textArea.getText().length());
}
}

@Override
protected void done() {
//this method is executed on the Event Dispatcher thread once doInBackground() returns
textArea.append("Stopped.");
textArea.setCaretPosition(textArea.getText().length());
startButton.setEnabled(true);
stopButton.setEnabled(false);
}
}

startButton.setEnabled(false);
stopButton.setEnabled(true);
textArea.setText("");
worker = new Worker();
worker.execute();
}

private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
worker.cancel(true);
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {
new SwingWorkerDemo().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton startButton;
private javax.swing.JButton stopButton;
private javax.swing.JTextArea textArea;
// End of variables declaration
private SwingWorker worker = null;
}


Source code formatted with http://formatmysourcecode.blogspot.com/

Comments

Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word