Sunday, February 10, 2008

Updating UI Elements From Command Handlers

I struggled a bit with this tonight so I figured it was worth a post. I am piddling around with command handlers as part of my background work for my upcoming talk at EclipseCON (should I keep plugging EclipseCON, or is that enough already?), and one of my simple samples was building on the Hello World, Command PDE sample. I wanted a simple toggle command instead of the default push-style command, but I could not get the menu item to toggle state (checked versus unchecked) when I executed my command with the keybinding. A little searching led me to this newsgroup post, and an eventual solution.

The secret sauce seems to be:

Make your class implement IElementUpdater:

public class SampleHandler extends AbstractHandler implements IElementUpdater {

Implement said interface with your required logic (this code is for my particular case):

public void updateElement(UIElement element,
Map parameters) {
element.setChecked(this.image != null);

Now, you need to get the command service to call updateElement. The easiest way to do this is in your execute method like so:

public Object execute(ExecutionEvent event) throws ExecutionException {

//... actually do something here ...

// Refresh the UI elements
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
ICommandService service = (ICommandService) window.getService(ICommandService.class);
service.refreshElements(event.getCommand().getId(), null);
return null;

No comments: