SwingCommand part 3 – Showing Progress
The progress animation triggered by the TaskListener in the previous example would at least inform the user that a SwingCommand is executing. However, sometimes it may be useful for a long running command to show publish interim results, or simply post more descriptive progress updates.
To help with this, as well as allowing you to set the generic type for parameters to your SwingCommand, the SwingCommand class also allows you to specify a generic type for a progress update. The following example demonstrates perhaps a simple case, in which an Integer progress event is fired:
class ClearMessagesCommand extends SwingCommand<String,Integer> {
public ClearMessagesCommand() {
}
public Task<String,Integer> createTask() {
return new BackgroundTask<String,Integer>() {
public void doInBackground() throws Exception {
fireProgress(1);
String userName = getParameters();
Statement s = connection.createStatement();
s.execute("delete from Message where User = " + userName);
fireProgress(2);
}
public void doInEventThread() {
fireProgress(3);
}
};
}
}
SwingCommand<String,Integer> c = new ClearMessagesCommand();
c.execute("Nick");
c.addTaskListener(new TaskListenerAdapter<Integer>() {
public void progress(Task task, Integer progressDescription) {
progressLabel.setText("stage " + String.valueOf(progressDescription));
}
});
You could do more sophisticated things by firing progress, and progress events make it easy to update the UI safely – remember that these messages are received on the Swing Event thread even if fired from doInBackground().
For example, you could use this mechanism to gradually populate messages into an ‘inbox’ while reading mail messages from a remote server. Or you could send an Integer progress update representing a percentage value, to update a progress bar with the current percentage of work completed by a background thread.
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply