eclipseeclipse-plugineclipse-rcpe4

How to create a toggle/radio item in the menu/toolbar of an Eclipse e4 application?


What is the canonical way of creating a menu item that implements a toggle or radio state in an eclipse e4 rcp application?

It seems such a basic thing, but all the documentation I found relies on e3 API and creates dependencies to org.eclipse.ui, which is not allowed in e4.


Solution

  • One possible way that I use for a radio button menu which saves the radio button state in the part class.

    I use multiple Direct Menu Item entries with the type set to Radio.

    I set a Tag value (on the supplementary page of the menu item) to the value I want to associate with the menu item.

    I use the same handler for all of the menu items.

    In the handler I inject the MPart and the MItem:

    @Execute
    public void execute(final MPart part, final MItem mitem)
    {
      // Only take action on the selected radio item
    
      if (!mitem.isSelected())
        return;
    
      // The tag value specifying the radio state
    
      String tag = mitem.getTags().get(0);
    
      // Get the part class
    
      MyPart myPart = (MyPart)part.getObject();
    
      // tell the part about the state change
    
      myPart.setState(tag);
    }
    

    Instead of the MPart you could also use any class that is in the Eclipse Context - such as one declared as @Creatable and @Singleton.