logo

Featured Content:

New blogsite launched. New open source swingcommand java library released.


Selected Recent Projects:

2002 - JPMorganChase - development of Fixed Income trading platform

2006 - Object Definitions selected to help BNP Paribas in development of Credit Risk front end

2008 - Swing Front end for Dresdner Kleinwort's Fixed Income Trading System

 

Home | About | Contact

headingSwingCommand - 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:

//Here I have updated the ClearMessagesCommand to publish progress messages as a Integer

  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.