我有一组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
,但没有说明monitor
期间performRead(_fileName, monitor);
内发生的事情
我该如何解决这个问题?
答案 0 :(得分:10)
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()
方法。