Eclipse RCP
20.09.2010 - 24.09.2010, Hamburg
git
07.10.2010 - 08.10.2010, Essen
16.08.2009

Contributing commands to context menus

In the following post I’ll show how one creates context menus for structured viewers in Eclipse RCP applications and how to contribute Eclipse commands to such a context menu:

Eclipse RCP context menu

Creating the context menu

To create a context menu that can be filled by contributions to org.eclipse.ui.menus, you have to create a JFace MenuManager. The place where the contributions are to be added should be marked using a Separator:

MenuManager menuManager = new MenuManager();
menuManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));

A SWT menu is created from that and set to the SWT widget:

table.setMenu(menuManager.createContextMenu(table));

You also have to register the context menu to the workbench so it knows about it and can add the contributed items. You should also register your viewer as selection provider:

getSite().registerContextMenu(menuManager, tableViewer);
getSite().setSelectionProvider(tableViewer);

Contributing to the menu

After you’ve added a context menu to your view, you can contribute commands to the context menu using the locationURI popup:<viewId>:

<menuContribution locationURI="popup:de.ralfebert.someview">
    <command
        commandId="de.rcpbuch.somecommand"
        icon="icons/alt_window_16.gif"
        style="push">
    </command>
</menuContribution>

Using the default menu item to handle the double-click event

SWT menus can have a default item that is set using setDefaultItem(...). Such menu items are shown in bold on Windows to indicate that this is the menu item that handles the double-click on the widget. Unfortunately, this is currently not supported directly for JFace MenuManagers / command contributions. But this feature can be sneaked in using a little utility class.

ContextMenu

I built a utility class that creates a context menu given a structured viewer and a workbench part site. ContextMenu creates a new context menu and does all the steps which are necessary to prepare the menu for contributions:

new ContextMenu(tableViewer, getSite(), true);

Additionally, ContextMenu supports contributing default menu items. The last argument is called defaultItemHandling. If you activate defaultItemHandling, the menu is enhanced so that the first command contribution whose contribution id ends with “.default” is set as default item for the menu and handles the double-click event in the structured viewer.

The class is part of de.ralfebert.rcputils, you can get it here: ContextMenu

I'm looking forward to your comments:

Schulungen

Eclipse RCP

Ralf Ebert | Blog | Eclipse RCP | Contributing commands to context menus