Search code examples
eclipse-plugine4

Update Checked State of Handler in E4


In E3 we had a couple of handlers that were to be checked, and so the handler had to figure out when to be checked. Back then that was an easy task:

public class MyHandler extends AbstractHandler implements IElementUpdater {
    @Override
    public void updateElement(UIElement element, Map parameters) {
        element.setChecked(calculateCheckState());
    }
}

I found this similar question, but it's much broader (updating all commands, while I only want to set the checked state whenever the framework seems it necessary). Since tool and menu items can be check or radio items, this has to be possible somehow.

So how do I set the check state of a handler in E4?


Solution

  • You can set the check (selected) state in the @CanExecute method of the handler using something like:

    @CanExecute
    public boolean canExecute(MItem item)
    {
      item.setSelected(... checked state ....);
    
      return true;
    }
    

    For a menu item the @CanExecute method is called every time the menu is displayed.

    For a tool bar item you may need to use the IEventBroker UIEvents.REQUEST_ENABLEMENT_UPDATE_TOPIC event to force the method to run.

    eventBroker.send(UIEvents.REQUEST_ENABLEMENT_UPDATE_TOPIC, argument);
    

    argument can be

    • UIEvents.ALL_ELEMENT_ID to update all items.
    • The id of a single item to be updated.
    • A Selector (org.eclipse.e4.ui.workbench.Selector) to select the items to be updated.