RSS

Search Engine

Wednesday, June 30, 2010

Progress report

If you perform long running operations you should provide the user some information about the long running job. A good way of doing this is to show a progress indicator or a progress dialog.

Create a new project "de.vogella.rcp.intro.progress" with "Hello RCP" as a template. Create the command "de.vogella.rcp.intro.progress.showDialog" with the default handler "de.vogella.rcp.intro.progress.handler.ShowDialog". Create the handler class.

   
package de.vogella.rcp.intro.progress.handler;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.handlers.HandlerUtil;

public class ShowDialog extends AbstractHandler {

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
ProgressMonitorDialog dialog = new ProgressMonitorDialog(HandlerUtil
.getActiveShell(event).getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) {
monitor
.beginTask("Doing something timeconsuming here",
100);
for (int i = 0; i < 10; i++) {
if (monitor.isCanceled())
return;
monitor.subTask("I'm doing something here " + i);
sleep(1000);
monitor.worked(i);
}
monitor.done();
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

return null;
}

private void sleep(Integer waitTime) {
try {
Thread.sleep(waitTime);
} catch (Throwable t) {
System.out.println("Wait time interrupted");
}
}

}

Add this command to the menu.

Run the application. Your command should open a dialog which show the process.

0 comments:

Post a Comment