Quantcast
Viewing all articles
Browse latest Browse all 14

Defining menu entries (commands) at runtime in Eclipse RCP

A common question I receive is how menu entries can be defined at runtime in an RCP application. The following gives an example how this can be done.

Create the RCP project “de.vogella.rcp.commands.runtimecommands” using the “Hello RCP” template.

Define a menu contribution. Maintain the class “de.vogella.rcp.commands.runtimecommands.DefineCommands” in this menu contribution.

<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>

   <extension
         id="application"
         point="org.eclipse.core.runtime.applications">
      <application>
         <run
               class="de.vogella.rcp.commands.runtimecommands.Application">
         </run>
      </application>
   </extension>
   <extension
         point="org.eclipse.ui.perspectives">
      <perspective
            name="RCP Perspective"
            class="de.vogella.rcp.commands.runtimecommands.Perspective"
            id="de.vogella.rcp.commands.runtimecommands.perspective">
      </perspective>
   </extension>
   <extension
         point="org.eclipse.ui.menus">
      <menuContribution
            class="de.vogella.rcp.commands.runtimecommands.DefineCommands"
            locationURI="menu:org.eclipse.ui.main.menu">
      </menuContribution>
   </extension>

</plugin>

Create the following class.

package de.vogella.rcp.commands.runtimecommands;

import org.eclipse.swt.SWT;
import org.eclipse.ui.menus.CommandContributionItem;
import org.eclipse.ui.menus.CommandContributionItemParameter;
import org.eclipse.ui.menus.ExtensionContributionFactory;
import org.eclipse.ui.menus.IContributionRoot;
import org.eclipse.ui.services.IServiceLocator;

public class DefineCommands extends ExtensionContributionFactory {

	@Override
	public void createContributionItems(IServiceLocator serviceLocator,
			IContributionRoot additions) {
		CommandContributionItemParameter p = new CommandContributionItemParameter(
				serviceLocator, "",
				"org.eclipse.ui.file.exit",
				SWT.PUSH);
		p.label = "Exit the application";
		p.icon = Activator.getImageDescriptor("icons/alt_window_16.gif");

		CommandContributionItem item = new CommandContributionItem(p);
		item.setVisible(true);
		additions.addContributionItem(item, null);
	}

}

Run the example, your application should have the Exit command in the menu.

Thanks to Robert Einsle for the tip.

This description has also be added to my Eclipse command tutorial.


Viewing all articles
Browse latest Browse all 14

Trending Articles