Saturday, August 11, 2012

Progress Bar

The performance testing requires a very long time, we need to know the progress of the testing.
Progress bar is a common choice.Progress bar is provided as a component by Java SWT. To add a progress bar, following steps can be used:
1. Create ProgressBar object, and choose the style, such as: ProgressBar bar1 = new ProgressBar (shell, SWT.HORIZONTAL | SWT.SMOOTH);.
2. Set the maximum value and minimum value, bar1.setMaximum(100);
3. Set the progress of the ProgressBar in a long time task, progressBar.getSelection() + 1.

Progress bar should be used with thread. The threads that are not UI thread cannot write the UI directly, otherwise the UI will be frozen, no more operations can be done with the UI. It is the same reason that the progress bar must update the UI in a separate thread.

Here is how I did to create the progress bar:

final ProgressBar progressBar = new ProgressBar(composite, SWT.SMOOTH);
    FormData fd_progressBar = new FormData();
    fd_progressBar.top = new FormAttachment(0);
    fd_progressBar.right = new FormAttachment(100, -42);
    progressBar.setLayoutData(fd_progressBar);
    class ProgressBarRunning extends Thread{
         long testRuntime = Integer.parseInt(text_1.getText());
         public void run() {
      for (int i = 0; i < 100; i++) {
  try {
                    Thread.sleep(testRuntime/100);
                } catch (InterruptedException e) {
               e.printStackTrace();
}
display.asyncExec(new Runnable() {
      public void run() {
if (progressBar.isDisposed())
    return;
progressBar.setSelection(progressBar.getSelection() + 1);
        }
   });
  }
  }
}

In the above code, the first thread decides how long the progress bar increase. The second thread updates the progress bar.


1 comment:

  1. Good, it would be better if you can include a screenshot to show what the bar looks like.

    ReplyDelete