I have a set of APIs that do file operations e.g. saveToFile(CustomObject objectToSave);
Since a file operation could be lengthy I decided that some indication should be shown to the user e.g. progress bar.
I read about a ProgressMonitorDialog
and so I tried it, but it doesn't exactly work as I need (or better I don't know how to use it properly).
Currently I do:
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();
}
});
This code shows a progress dialog very fast and ends, but the problem is that on a slower PC this would stack until the Utils.saveToFile
returned, while I have no idea how to indicate intermediate process until the save is completed.
I found a thread mentioning about IProgressMonitor.UNKNOWN
but it does not say about what happens in monitor
during the performRead(_fileName, monitor);
How would I solve this?
ProgressMonitorDialog
is a tricky piece of code. I guess the part you are missing is IProgressMonitor#worked(int)
which will "grow" the progress bar. Below is a code example that should clarify how to use it:
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();
}
}
}
It will look something like this:
For your special case of using Utils.saveToFile
you could hand the IProgressMonitor
over to this method and call the worked()
method from there.