概要

ProgressMonitorで処理の進捗を表示します。

サンプルコード

final ProgressMonitor monitor = new ProgressMonitor(
    this, "message", "note", 0, 100);
monitor.setProgress(0);
worker = new SwingWorker<String, String>() {
  @Override public String doInBackground() {
    int current = 0;
    int lengthOfTask = 120; //list.size();
    while (current < lengthOfTask && !isCancelled()) {
      try {
        Thread.sleep(50);
      } catch (InterruptedException ie) {
        return "Interrupted";
      }
      setProgress(100 * current / lengthOfTask);
      publish(current + "/" + lengthOfTask);
      current++;
    }
    return "Done";
  }
  @Override protected void process(java.util.List<String> chunks) {
    for (String message : chunks) {
      monitor.setNote(message);
    }
  }
  @Override public void done() {
    runButton.setEnabled(true);
    monitor.close();
    String text = null;
    if (isCancelled()) {
      text = "Cancelled";
    } else {
      try {
        text = get();
      } catch (Exception ex) {
        ex.printStackTrace();
        text = "Exception";
      }
    }
    //System.out.println(text);
    area.append(text + "\n");
    area.setCaretPosition(area.getDocument().getLength());
    //appendLine(text);
  }
};
worker.addPropertyChangeListener(new ProgressListener(monitor));
worker.execute();
view all

解説

上記のサンプルでは、SwingWorkerを使ったタスクの進捗状態をProgressMonitorで表示しています。


ProgressListenerは、TutorialProgressMonitorDemo.javaを変更して使用しています。

class ProgressListener implements PropertyChangeListener {
  private final ProgressMonitor monitor;
  public ProgressListener(ProgressMonitor monitor) {
    this.monitor = monitor;
    this.monitor.setProgress(0);
  }
  @Override public void propertyChange(PropertyChangeEvent e) {
    Object o = e.getSource();
    String strPropertyName = e.getPropertyName();
    if ("progress".equals(strPropertyName) && o instanceof SwingWorker) {
      SwingWorker task = (SwingWorker) o;
      monitor.setProgress((Integer) e.getNewValue());
      if (monitor.isCanceled() || task.isDone()) {
        task.cancel(true);
      }
    }
  }
}

参考リンク

コメント