我有一组执行文件操作的 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
返回,而我不知道如何指示中间过程直到保存完成。
我找到了一个 thread提到 IProgressMonitor.UNKNOWN
但它没有说明在 performRead(_fileName, monitor);
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
交给此方法并调用 worked()
方法那里。
关于java - 在 Eclipse 4 中正确使用 ProgressMonitorDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12986912/