ProgressMonitorで処理の進捗を表示
Total: 15146
, Today: 1
, Yesterday: 1
Posted by aterai at
Last-modified:
概要
ProgressMonitor
で処理の進捗を表示します。
Screenshot
Advertisement
サンプルコード
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
はTutorial
のProgressMonitorDemo.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);
}
}
}
}
参考リンク
- ProgressMonitor (Java Platform SE 8)
- How to Use Progress Bars (The Java™ Tutorials)
- ProgressMonitorがダイアログを表示するまでの待ち時間
- 処理時間が短くて
ProgressMonitor
が表示されない場合の待ち時間をテスト
- 処理時間が短くて
- [JDK-6445283] ProgressMonitorInputStream not large file aware (>2GB) - Java Bug System