• category: swing folder: ProgressMonitor title: ProgressMonitorで処理の進捗を表示 tags: [ProgressMonitor, SwingWorker, PropertyChangeListener, JProgressBar] author: aterai pubdate: 2010-02-15T14:18:06+09:00 description: ProgressMonitorで処理の進捗を表示します。 image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTRQXIAu4I/AAAAAAAAAg4/bh8niw_k5AE/s800/ProgressMonitor.png

概要

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

サンプルコード

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(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 in GitHub: Java, Kotlin

解説

上記のサンプルでは、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);
      }
    }
  }
}

参考リンク

コメント