正确使用Eclipse 4中的ProgressMonitorDialog

我有一组API来执行文件操作,例如saveToFile(CustomObject objectToSave);

由于文件操作可能很长,我决定应该向用户显示某些指示,例如进度条。

我读了一个关于ProgressMonitorDialog ,所以我试了一下,但它并没有完全按照我的需要工作(或者更好,我不知道如何正确使用它)。

目前我这样做:

 ProgressMonitorDialog progressDialog = new ProgressMonitorDialog(theShell); try { progressDialog.run(false, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Saving your data", 100); try { Utils.saveToFile(objectToSave); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } monitor.done(); } }); 

这段代码非常快速地显示了一个进度对话框,但问题是在较慢的PC上,这将堆叠直到Utils.saveToFile返回,而我不知道如何在保存完成之前指示中间进程。

我找到了一个关于IProgressMonitor.UNKNOWN的线程,但它没有说明在performRead(_fileName, monitor);期间monitor中发生了什么performRead(_fileName, monitor);

我该如何解决这个问题?

ProgressMonitorDialog是一段棘手的代码。 我想你缺少的那部分是IProgressMonitor#worked(int) ,这将“增长”进度条。 下面是一个代码示例,应该说明如何使用它:

 public class Progress { public static void main(String[] args) { // Create your new ProgressMonitorDialog with a IRunnableWithProgress try { // 10 is the workload, so in your case the number of files to copy IRunnableWithProgress op = new YourThread(10); new ProgressMonitorDialog(new Shell()).run(true, true, op); } catch (InvocationTargetException ex) { ex.printStackTrace(); } catch (InterruptedException ex) { ex.printStackTrace(); } } private static class YourThread implements IRunnableWithProgress { private int workload; public YourThread(int workload) { this.workload = workload; } @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { // Tell the user what you are doing monitor.beginTask("Copying files", workload); // Do your work for(int i = 0; i < workload; i++) { // Optionally add subtasks monitor.subTask("Copying file " + (i+1) + " of "+ workload + "..."); Thread.sleep(2000); // Tell the monitor that you successfully finished one item of "workload"-many monitor.worked(1); // Check if the user pressed "cancel" if(monitor.isCanceled()) { monitor.done(); return; } } // You are done monitor.done(); } } } 

它看起来像这样:

在此处输入图像描述

对于使用Utils.saveToFile特殊情况,您可以将IProgressMonitor交给此方法并从那里调用Utils.saveToFile worked()方法。