Vge Shi
Vge Shi

Reputation: 213

Adding new menu item to a menu bar defined in plugin.xml programmatically in RCP application

I have an eclipse rcp application, with menu extension. There is one menu item "File"

Now I want to add a new menu item from one of the views (I know this is a wrong design, just want to test it)

in the method createPartControl of my class that extends ViewPar, I have:

Menu menuBar =  parent.getShell().getMenuBar(); //I get the Menu that contains File
MenuItem editMenuItem = new MenuItem(menuBar, SWT.CASCADE);

editMenuItem.setText("Edit");
Menu editMenu = new Menu(parent.getShell(), SWT.DROP_DOWN);
editMenuItem.setMenu(editMenu);

When in Debug I watch the parent.getShell().getMenuBar() I get:

Menu {File, Edit}

But in application window I see only File menu.

Upvotes: 2

Views: 1997

Answers (1)

greg-449
greg-449

Reputation: 111142

To do this programatically rather than via an extension point it looks like you have to use IMenuService and add a contribution factory:

IMenuService menuService = (IMenuService)PlatformUI.getWorkbench().getService(IMenuService.class);

menuService.addContributionFactory(factory);

factory is a class derived from AbstractContributionFactory which provides the menu items.

This example is from http://wiki.eclipse.org/Menu_Contributions/Search_Menu

AbstractContributionFactory searchContribution = new AbstractContributionFactory(
           "menu:org.eclipse.ui.main.menu?after=navigate") {
       public void createContributionItems(IMenuService menuService,
               List additions) {
           MenuManager search = new MenuManager("Se&arch",
                   "org.eclipse.search.menu");

           search.add(new GroupMarker("internalDialogGroup"));
           search.add(new GroupMarker("dialogGroup"));
           search.add(new Separator("fileSearchContextMenuActionsGroup"));
           search.add(new Separator("contextMenuActionsGroup"));
           search.add(new Separator("occurencesActionsGroup"));
           search.add(new Separator("extraSearchGroup"));

           additions.add(search);
       }

       public void releaseContributionItems(IMenuService menuService,
               List items) {
           // nothing to do here
       }
   };

menuService.addContributionFactory(searchContribution);

Upvotes: 2

Related Questions