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:
Image may be NSFW.
Clik here to view.
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
:
MenuManagermenuManager=newMenuManager();menuManager.add(newSeparator(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>
:
<menuContributionlocationURI="popup:de.ralfebert.someview"><commandcommandId="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:
newContextMenu(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