Version 3.1
Copyright © 2009, 2010, 2011, 2012, 2013, 2014 vogella GmbH
22.01.2014
Table of Contents
This tutorial describes the Eclipse 3.x API which is used for Eclipse IDE plug-in development.
For Eclipse RCP you should use the new Eclipse 4 API which is described in the Eclipse RCP tutorial.
Eclipse IDE extensions use the commands framework to contribute actions to the user interface. This concept is based on extension points.
This description explains the usage of commands in Eclipse IDE extensions. To define and use a command you have to define three extensions. The following extension points are relevant to define a menu or toolbar contribution for an Eclipse plug-in.
Table 1.
| Extension Point | Description |
|---|---|
| org.eclipse.ui.command | Declarative description of the component |
| org.eclipse.ui.handlers | Defines the behavior, e.g., the Java class which should be called |
| org.eclipse.ui.menu | Where and how should the command be included in the user interface, e.g., menu, popup menu, toolbar, etc. |
A command in Eclipse is a declarative description of a component and is independent from the implementation details.
A command can be categorized, assigned to the user interface and a key binding can be defined for the command. The behavior of a command is defined via a handler.
The
org.eclipse.ui.menu
extension point is used to define where the command is visible in the
application, e.g., you could define that the command is visible in the
application menu or in a
view
menu.

The menuContribution contribution has an ID value which allow to identify the contribution.
menuContribution
has an
locationURI
attribute which allows to
define where in the user interface a
command
is displayed. This different attribute values are summarized in the
following table.
Table 2. Location URIs
| Contribution to | Description | Uri |
|---|---|---|
| Application menu | Displays the command in the menu of the application | menu:org.eclipse.ui.main.menu |
| Application toolbar | displays the command in the toolbar of the application | toolbar:org.eclipse.ui.main.toolbar |
| View toolbar | displays the command in the toolbar of the view | toolbar:viewId - For example to display a menu to view with the Id "View1" use "toolbar:View1". |
| Context menu / pop-up | Command is displayed in a context menu, e.g., right mouse click on an object | popup:ID |
Frequently you want to position a new command behind or before another command. For example the Save All menu entry should be positioned after the Save menu entry.
You can define the relative position of a command in this
locationURI
by using the
pattern
?before=ID
or
?after=ID.
The ID can be an existing separator name, menu ID, or item ID. The command will then be placed before or after the element with the corresponding ID.
For example if you want to add
a command to an
existing menu with
the
fileMenu
ID behind the menu
entry with the
oneEntry
ID use the
menu:fileMenu?after=oneEntry
locationURI .
The
org.eclipse.ui.handlers
extension point connects the command to a certain class which is
called once the command is executed.
The behavior of a command is
defined via
handlers. The handler is
the
class which is executed once the command is
called and must
implement
the
IHandler
interface from the
org.eclipse.core.commands
package.
In most cases you extend the
org.eclipse.core.commands.AbstractHandler
class which
provides a
default
implementation for the
IHandler
interface.
The
execute()
method is called if the handler is executed.
In the
execute()
method you get access to frequently used values
and services via the
HandlerUtil
class.
Handler can be defined with conditions (activeWhen) under which define the conditions under which the handlers are valid for a command. You can define several handlers for a command but only handler can be valid for a command at a certain point. Otherwise the Eclipse runtime will not enabled the command.
This tutorial assumes that you have basic understanding of development for the Eclipse platform. Please see Eclipse RCP Tutorial or Eclipse Plug-in Tutorial if you need any basic information.
We will create a command which will exit the application. Create a new RCP project "de.vogella.rcp.commands.first" using the "Hello RCP" template. Click on the plugin.xml and select the Extensions tab. Press the button.

Search for the extension "org.eclipse.ui.commands". Select it and press finish.

Create a new command by right-click on your extension point and by selecting New -> command.

Set the ID to "de.vogella.rcp.commands.first.commands.Exit" and the name to "Exit". Enter the class "de.vogella.rcp.commands.first.commands.ExitHandler" as defaultHandler.

Press the hyperlink "defaultHandler" to create the class which should extend "org.eclipse.core.commands.AbstractHandler".
package de.vogella.rcp.commands.first.commands; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.handlers.HandlerUtil; public class ExitHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { HandlerUtil.getActiveWorkbenchWindow(event).close(); return null; } }
The command which we defined should be used in a
menu. Add a extension
to the
org.eclipse.ui.menus
extension point.
Right-click on the
extension point and select
→ .

Create a new menu contribution with the "menu:org.eclipse.ui.main.menu" locationURI. Make sure this URL is correct spelled, otherwise your menu will not be shown.

Right-click your menucontribution and select → . Add a menu with the "File" label and the "fileMenu" ID.


Select your menu, right-click on it, select New-> Command. Maintain your commandID. Set the label to "Exit" and the tooltip to "Exits the application".

This should result in a plugin.xml file which looks like
the
following.
<?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.first.Application"> </run> </application> </extension> <extension point="org.eclipse.ui.perspectives"> <perspective name="RCP Perspective" class="de.vogella.rcp.commands.first.Perspective" id="de.vogella.rcp.commands.first.perspective"> </perspective> </extension> <extension point="org.eclipse.ui.commands"> <command defaultHandler="de.vogella.rcp.commands.first.commands.ExitHandler" id="de.vogella.rcp.commands.first.commands.Exit" name="Exit"> </command> </extension> <extension point="org.eclipse.ui.menus"> <menuContribution locationURI="menu:org.eclipse.ui.main.menu"> <menu id="fileMenu" label="File"> <command commandId="de.vogella.rcp.commands.first.commands.Exit" label="Exit" style="push" tooltip="Exit the application"> </command> </menu> </menuContribution> </extension> </plugin>
Run the example. You should see menu with the file and if you select the "Exit" entry you application should exit.

Create a new project "de.vogella.rcp.intro.commands.toolbar". Use the "RCP application with a view" as a template. Create a command "de.vogella.rcp.intro.commands.toolbar.Hello" with the default handler "de.vogella.rcp.intro.commands.toolbar.handler.Hello". This handler will open a JFace Dialog.
package de.vogella.rcp.intro.commands.toolbar.handler; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.handlers.HandlerUtil; public class Hello extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { MessageDialog.openInformation(HandlerUtil.getActiveWorkbenchWindow(event).getShell(), "Info", "Info for you"); return null; } }
Add a menucontribution to the "org.eclipse.ui.menus extension" point. Set the location URI to "toolbar:org.eclipse.ui.main.toolbar". Add a toolbar to your menu contribution.

Add the command "de.vogella.rcp.intro.commands.toolbar.Hello" to the toolbar. Assign a label and an icon to it.

Activate the application toolbar via ApplicationWorkbenchWindowAdvisor.java and set the configurer.setShowCoolBar(true); (
package de.vogella.rcp.intro.commands.toolbar; import org.eclipse.swt.graphics.Point; import org.eclipse.ui.application.ActionBarAdvisor; import org.eclipse.ui.application.IActionBarConfigurer; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchWindowAdvisor; public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor { public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { super(configurer); } public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) { return new ApplicationActionBarAdvisor(configurer); } public void preWindowOpen() { IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); configurer.setInitialSize(new Point(400, 300)); configurer.setShowStatusLine(false); configurer.setShowCoolBar(true); configurer.setTitle("RCP Application"); } }
The result should look like the following. If you select the element in the toolbar an information dialog should open.

You can also add a command directly to a view toolbar. For this we will extend the previous example. Change the class "Perspective" to the following (a stand-alone view does not have a own toolbar).
package de.vogella.rcp.intro.commands.toolbar; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; public class Perspective implements IPerspectiveFactory { public void createInitialLayout(IPageLayout layout) { String editorArea = layout.getEditorArea(); layout.setEditorAreaVisible(false); layout.setFixed(true); layout.addView(View.ID, IPageLayout.LEFT, 1.0f, editorArea); } }
Create a new menu contribution to the extension point "org.eclipse.ui.menus" with the locationURI: "toolbar:de.vogella.rcp.intro.commands.toolbar.view". ""toolbar:"" tells the system to add it to the toolbar while the second argument is the id of your view.
Create then a new command for this menucontribution and set the command id to "de.vogella.rcp.intro.commands.toolbar.Hello". Assign the label "Say Hello" to it.

Run the application to see your new view contribution.

The following adds a dropdown list to the application coolbar.
This creation is a bit strange. You create a helper drop-down command to which later the other (real) commands will be assigned to.
Therefore create a command with the id "referenceToMenuId". Maintain also the default handler. For example you could reuse "de.vogella.rcp.intro.commands.toolbar.handler.Hello".

Add a new menucontribution to the "org.eclipse.ui.menus" extension point. Set the location URI to "toolbar:org.eclipse.ui.main.toolbar". Add a toolbar to this extension and a new command to this new toolbar. As the id use "referenceToMenuId" give it a label and an icon and change the style to "pulldown".

Create a new menucontribution and set the locationURI to: "menu:referenceToMenuId"
Add your exiting command "de.vogella.rcp.intro.commands.toolbar.Hello" two times to this menu. Use different labels.

Run your application, it should now have a drop-down list in the application toolbar.

In this example you add a context menu to a SWT table widget. Create a new project "de.vogella.rcp.intro.commands.popup" based on the "RCP application with a view" example.
Create a new command with the
de.vogella.rcp.intro.commands.popup.showSelected
ID
and the name
Show.
In this example we will not use the default handler. Therefore
add the
org.eclipse.ui.handlers
extension point
to your plugin.xml file
and add a handler. The first
parameter is the
commandId and the
second
the class for the handler. Use
de.vogella.rcp.intro.commands.popup.handler.ShowSelected
as class name.

Implement now the code for your handler. I just print the selected elements to the console.
package de.vogella.rcp.intro.commands.popup.handler; import java.util.Iterator; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.handlers.HandlerUtil; public class ShowSelected extends AbstractHandler { @SuppressWarnings("unchecked") @Override public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event) .getActivePage().getSelection(); if (selection != null & selection instanceof IStructuredSelection) { IStructuredSelection strucSelection = (IStructuredSelection) selection; for (Iterator<Object> iterator = strucSelection.iterator(); iterator .hasNext();) { Object element = iterator.next(); System.out.println(element.toString()); } } return null; } }
Add a new menuContribution with the locationURI "popup:de.vogella.rcp.intro.commands.popup.view", where "de.vogella.rcp.intro.commands.popup.view" is the ID of your view which has been automatically created for you.
Right-click your new menuContribution and select New -> Command. Assign your command to the field "commandId". Label it "One Item selected".
Now you have add a MenuManager to your view. Select the
View
class and change it to the following.
package de.vogella.rcp.intro.commands.popup; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; public class View extends ViewPart { private TableViewer viewer; class ViewLabelProvider extends LabelProvider { @Override public Image getImage(Object obj) { return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT); } } @Override public void createPartControl(Composite parent) { viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); viewer.setContentProvider(ArrayContentProvider.getInstance()); viewer.setLabelProvider(new ViewLabelProvider()); viewer.setInput(getData()); // Create a menu manager and create context menu MenuManager menuManager = new MenuManager(); Menu menu = menuManager.createContextMenu(viewer.getTable()); // set the menu on the SWT widget viewer.getTable().setMenu(menu); // register the menu with the framework getSite().registerContextMenu(menuManager, viewer); // make the viewer selection available getSite().setSelectionProvider(viewer); }/** * Passing the focus request to the viewer's control. */@Override public void setFocus() { viewer.getControl().setFocus(); } private List<String> getData() { List<String> list = new ArrayList<String>(); list.add("One"); list.add("Two"); list.add("Three"); return list; } }
Run your application. If you perform a right-click on the table, your menu should become visible. If you select it menu then the names of the selected items should be written to the console.
For more advanced usages of Eclipse Commands please see Eclipse Commands Advanced.
Please consider a contribution
if this article helped you. It will help to maintain our content and our Open Source activities.
Writing and updating these tutorials is a lot of work. If this free community service was helpful, you can support the cause by giving a tip as well as reporting typos and factual errors.
If you find errors in this tutorial, please notify me (see the top of the page). Please note that due to the high volume of feedback I receive, I cannot answer questions to your implementation. Ensure you have read the vogella FAQ as I don't respond to questions already answered there.
This tutorial is Open Content under the CC BY-NC-SA 3.0 DE license. Source code in this tutorial is distributed under the Eclipse Public License. See the vogella License page for details on the terms of reuse.
http://wiki.eclipse.org/Platform_Command_Framework Command Framework wiki
http://wiki.eclipse.org/Command_Core_Expressions Commands Core Expressions
| TRAINING | SERVICE & SUPPORT |
|---|---|
| The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”. | The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers. |