vogella.de

Follow me on twitter
About Lars Vogel
Flattr this

Eclipse Commands Tutorial

Lars Vogel

Version 1.7

28.06.2010

Revision History
Revision 0.130.03.2009Lars Vogel
Created
Revision 0.2 - 0.411.04.2009 - 16.04.2009Lars Vogel
bugfixes and improvements
Revision 0.530.05.2009Lars Vogel
Update to Eclipse 3.5 (Galileo)
Revision 0.6 - 1.508.07.2009 - 02.12.2009Lars Vogel
bugfixes and improvements
Revision 1.7 28.06.2010Lars Vogel
Update to Eclipse 3.6 (Helios)

Eclipse Commands

This article describes the usage of Eclipse commands. It describes how to create commands, handlers, add commands into the menu, pop-ups, views and editors and the usage of expressions to restrict UI contributions. The usage of keybindings is also explained.

This article is based on Eclipse Helios (3.6).


Table of Contents

1. Eclipse Commands - Overview
1.1. Overview
1.2. Location URI - User interface
1.3. Command Handler
2. Commands and menus
2.1. Assumptions
2.2. Defining commands
2.3. Using commands in menus
3. Commands and toolbars
3.1. Overview
3.2. Application toolbar (coolbar)
3.3. Contribution to the View Toolbar
3.4. Drop down list
4. Commands and context menus
5. Enabled when (visible when)
6. Keybindings for Commands
6.1. Overview
6.2. Keybinding
6.3. Defining your own schema
7. Eclipse standard commands
7.1. Overview
7.2. Example
8. Calling commands from a button
9. Providing your own expression
10. Using parameters in commands
11. Defining commands at runtime
12. Thank you
13. Questions and Discussion
14. Links and Literature
14.1. Source Code
14.2. Eclipse Commands Resources
14.3. vogella Resources

1. Eclipse Commands - Overview

1.1. Overview

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 can be defined via a handler.

Therefore to define and use a command you need

  • Command - Declarative description of the component

  • Handler - Defines the behavior

  • UI Assignment - Where and how should the command be included in the UI

Commands are defined via the extension point org.eclipse.ui.commands.

The following example used are based on Eclipse RCP but the concept also applies to general Eclipse plugin development.

1.2. Location URI - User interface

Commands can be used in menus, toolbars and / or context menus. Where and how these commands are displayed is defined via a location URI.

Table 1. 

Contribution toDescriptionUri
Application menuDisplays the command in the menu of the application"menu:org.eclipse.ui.main.menu"
Application toolbardisplays 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:Views1".
Content menu / pop-upCommand is displayed in a content menu, e.g. right mouse click on an objectn.a.

1.3. Command Handler

The behavior of a command is defined via handlers. You can define several handlers for a command but only only handler can be valid for a command at a certain point otherwise the command is not active. The handler is the class which will be executed once the command is called. A command handler must implement the interface org.eclipse.core.commands.IHandler.

IHandler (which is implemented by org.eclipse.core.commands.AbstractHandler) defines the following important methods which can be implemented:

  • isEnabled: Called during instantiation, defines if this action is enabled

  • isHandled: Defines if the handler can be called or not

  • execute: Coding which perform the action

  • fireHandlerChanged: needs to be called if isEnabled is changed.

Tip

The class HandlerUtil provides access methods to the important Eclipse services.

Handler can be defined with conditions (activeWhen) under which they are valid handlers for the command. If more then one handler is valid for a given selection the Eclipse runtime cannot decided which one is used and the command will not be enabled.

2.  Commands and menus

2.1. Assumptions

I assume you know already how to create a Eclipse RCP application. See Eclipse RCP - Tutorial for details.

2.2. Defining commands

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 "Add" button.

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

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

Tip

If you only see an "Generic" entry you most likely have not downloaded "Eclipse for RCP/Plug-in Developers". Please see Eclipse Installation .

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 this class and select "org.eclipse.core.commands.AbstractHandler" as Superclass.

Implement the following coding. Afterwards your new command is ready to be used.

			
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;
	}

}

		

2.3. Using commands in menus

The command which we defined should be used in a menu. Add the extension point "org.eclipse.ui.menus" to your application similar to adding the extension "org.eclipse.ui.commands". Right click on the extension point and select new -> menuContribution.

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

Right click your menucontribution and select New -> Menu. Add a menu with the label "File" and the id "fileMenu".

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".

Your work 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.

3. Commands and toolbars

3.1. Overview

You can add commands to the application toolbar and to a view toolbar.

Tip

You can define the relative position of a command via 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.

3.2.  Application toolbar (coolbar)

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".

				
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:

3.3. Contribution to the View Toolbar

You can also add a command directly to a view toolbar. For this we will extend the previous example.

Change Perspective.java to the following (a standalone 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".

Tip

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.

3.4. Drop down list

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 exapmle you could re-use "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"

Tip

referenceToMenuId is the ID we used earlier in the command.

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.

Tip

Add the command "referenceToMenuId" to your exiting view toolbar contribution to get the drop-down menu also in your view.

4. Commands and context menus

Now lets add a ContextMenu to a table. 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 ID "de.vogella.rcp.intro.commands.popup.showSelected" and the name "Show".

In this example we will not use the default handler. Therefore add the extension point "org.eclipse.ui.handlers" to your plugin.xml and add a handler. The first parameter is the commandId and the second the class for the handler. We will use class "de.vogella.rcp.intro.commands.popup.handler.ShowSelected".

Implement now the coding 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 View.java and in the method createPartControl add the following:

				
	public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
				| SWT.V_SCROLL);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setInput(getViewSite());
		// This is new code
		// First we create a menu Manager
		MenuManager menuManager = new MenuManager();
		Menu menu = menuManager.createContextMenu(viewer.getTable());
		// Set the MenuManager
		viewer.getTable().setMenu(menu);
		getSite().registerContextMenu(menuManager, viewer);
		// Make the selection available
		getSite().setSelectionProvider(viewer);
	}

			

Run your application. On right mouse click the menu should be visible. If you select it menu then the names of the selected items should be written to the console.

5.  Enabled when (visible when)

The command framework allows to restrict the availability and visibility of commands, handlers and ui contributions via the core expressions .

In this example we want the command only be enabled if one item from a list of items is selected.

Create a new project "de.vogella.rcp.commands.enable" based on the "RCP application with a view" example.

Add a command with the ID "de.vogella.rcp.commands.enable.command". Add this command to the menu and the toolbar and create the following default handler.

			
package de.vogella.rcp.commands.enable.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 Command extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		MessageDialog.openInformation(HandlerUtil.getActiveWorkbenchWindow(
				event).getShell(), "Info", "Info for you");

		return null;
	}

}

		

Select plugin.xml and add "org.eclipse.core.expressions" as a dependency. Select then the Extensions tab and add the extensions org.eclipse.core.expressions.definitions.

Using right mouse click add a definition "oneElementSelected". Add a "with" variable "selection".

Tip

"selection" is a predefined variable which will be calculated automatically by Eclipse. See core expressions for additional variables you can use. For example for a popup menu "activeMenuSelection" provides the selection.

On the "activeMenuSelection" right mouse click and add a count with the value "1". The result should look like

On your handler, right mouse click and select enabledWhen. Right mouse click and add a "reference" to it with the value "oneElementSelected". The result should look like.

The expression were are using is based on "selection". Therefore the list must register itself as selection provider to inform the workbench in case something is selected. Therefore add "getSite().setSelectionProvider(viewer);" in createPartControl of View.java.

			
public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
				| SWT.V_SCROLL);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setInput(getViewSite());
		// Makes the selection available to the workbench
		getSite().setSelectionProvider(viewer);
	}
	
		

If you now run the application your command should only be enabled if one element in the list is selected.

Tip

You can also only display the menu if one item is selected. The approach is the same but you only define the restriction on the menu contribution directly (visible when on the command in the menu). For a command in the toolbar the definition would look like:

6. Keybindings for Commands

6.1. Overview

Via keybindings you can define shortcuts for your commands. Eclipse uses a default key configuration scheme. The challenge for Eclipse RCP application is that you usually do not want to have the standard Eclipse IDE shortcuts available in your application.

The following therefore explains how to create keybindings and how to overwrite the default key binding schema of Eclipse.

To define and use your own scheme you need:

  • Define a scheme in extension point "org.eclipse.ui.bindings"

  • Assign this scheme to the keybindings you defined

  • Have a product created

  • Define the file "plugin_customization.ini" and set the scheme for the product via a property.

6.2. Keybinding

Create a new project "de.vogella.rcp.intro.commands.keybinding" using the "Hello RCP" template, declare command "de.vogella.rcp.intro.commands.keybinding.hello" with a default handler "de.vogella.rcp.intro.commands.keybinding.HelloHandler" which prints out "Hello" to the console

Add the extension point "org.eclipse.ui.bindings" to your project. Right click in this extension point, select New-> Key.

Select as schemaID "org.eclipse.ui.defaultAcceleratorConfiguration" this is the workbench default and will make sure you keybinding is valid in the whole application. The commandId is the ID of the command you just created. The sequence is the shortcut key for calling the command. M1 represents the Cntr key.

If you now run it the keybinding should work and if you press Cntrl+1 the message on the console should be visible.

6.3. Defining your own schema

Add now another key binding "Cntr+N" to the command "de.vogella.rcp.intro.commands.keybinding.hello" . Try it. This will not work as it is conflicting with the Eclipse default schema.

Right click in this extension point "org.eclipse.ui.bindings", select New-> Scheme. Create a schema with the id "MyScheme".

Assign the scheme id to your commands.

Define a product. See Defining a product for Eclipse RCP for details.

Create the following file "plugin_customization.ini" and put it in your main directory

				
org.eclipse.ui/KEY_CONFIGURATION_ID=myscheme
			

If you now run your product the "Cntr+N" shortcut should work.

7. Eclipse standard commands

7.1. Overview

Eclipse provides lots of standard commands which you can re-use. Just press on the "Browse button" while defining your commandId to see the available standard commands. For example the screenshot shows the usage of the standard about dialog command.

The advantage of using standard commands is that you get the keybinding, icons, etc for free.

Tip

Standard commands sometimes map to actions which are contributed via ActionFactory in the class ApplicationActionBarAdvisor. If the ActionFactory returns an IAction you need to register this action. If not these commands are inactive in your menu. For example the following made the reset perspective and welcome command active.

				
// Method belongs to class ApplicationActionBarAdvisor
	@Override
	protected void makeActions(IWorkbenchWindow window)
	{
		IWorkbenchAction quickStartAction = ActionFactory.INTRO.create(window);
		register(quickStartAction);
		IWorkbenchAction resetView = ActionFactory.RESET_PERSPECTIVE
				.create(window);
		register(resetView);
	}
			

7.2. Example

You can also use standard command and define a new handler for this command, e.g. you can use the standard Eclipse delete command (org.eclipse.ui.edit.delete).

Tip

To find the id of existing commands you can you the Eclipse Plugin Spy.

You can use the extension point "org.eclipse.ui.handlers" to define new handlers for the standard commands.

Tip

Eclipse requires you to have only one active handler at the time therefore you have to use the "activeWhen" restriction on the handler to make it more special then the standard binding. To use for example delete in several views with different handlers use "activeWhen" with the variable "activePartId" and as the value your view id.

Create a new RCP application "de.vogella.rcp.commands.standardcommands" with the template "Hello RCP".

Create a handler for the command "org.eclipse.ui.edit.delete" which display a message box. Add the command "org.eclipse.ui.edit.delete" to the menu.

The result should look like the following.

8. Calling commands from a button

You can call a command, e.g. in this example "add.command" from a button via the following coding.

			
button.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				IHandlerService handlerService = (IHandlerService) getSite()
						.getService(IHandlerService.class);
				try {
					handlerService.executeCommand("add.command", null);
				} catch (Exception ex) {
					throw new RuntimeException("add.command not found");
				}

			}
		});

		

9. Providing your own expression

You can write your own Java class which can be used define a variable which can then be used to define if a certain UI element shall be active or not. For example you can read the authorization of the user from your own class and then return the value which is assign to the user. This return value can then be used in a visible / enabled statement. This is similar to the usage of the core expressions we have seen earlier.

Create a RCP application "de.vogella.rcp.commands.sourceprovider" with the template "Hello RCP".

We will create a source provider. This source provider can provide variables which can be used in defining the visibility of commands. Add the extension point "org.eclipse.ui.services" to your plugin and create a new service provider.

This defines a service which provides the variable "de.vogella.rcp.commands.sourceprovider.active" to the workbench. This class must implement ISourceProvider. This value can then be used similar to a core expression. Maintain the following code.

			
package de.vogella.rcp.commands.sourceprovider;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.ui.AbstractSourceProvider;
import org.eclipse.ui.ISources;

public class CommandState extends AbstractSourceProvider {
	public final static String MY_STATE = "de.vogella.rcp.commands.sourceprovider.active";
	public final static String ENABLED = "ENABLED";
	public final static String DISENABLED = "DISENABLED";
	private boolean enabled = true;


	@Override
	public void dispose() {
	}

	// We could return several values but for this example one value is sufficient
	@Override
	public String[] getProvidedSourceNames() {
		return new String[] { MY_STATE };
	}
	
	// You cannot return NULL
	@SuppressWarnings("unchecked")
	@Override
	public Map getCurrentState() {
		Map map = new HashMap(1);
		String value = enabled ? ENABLED : DISENABLED;
		map.put(MY_STATE, value);
		return map;
	}

	

	// This method can be used from other commands to change the state
	// Most likely you would use a setter to define directly the state and not use this toogle method
	// But hey, this works well for my example
	public void toogleEnabled() {
		enabled = !enabled ;
		String value = enabled ? ENABLED : DISENABLED;
		fireSourceChanged(ISources.WORKBENCH, MY_STATE, value);
	}

}

		

Create two commands "de.vogella.rcp.commands.sourceprovider.command1" and "de.vogella.rcp.commands.sourceprovider.command2". Create any handler you want for the first command. Command2 will be used to change the state in our ISourceProvider. Maintain the following code for the handler.

			
package de.vogella.rcp.commands.sourceprovider.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.services.ISourceProviderService;

import de.vogella.rcp.commands.sourceprovider.CommandState;

public class Command2 extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// Get the source provider service
		ISourceProviderService sourceProviderService = (ISourceProviderService) HandlerUtil
				.getActiveWorkbenchWindow(event).getService(
						ISourceProviderService.class);
		// Now get my service
		CommandState commandStateService = (CommandState) sourceProviderService
				.getSourceProvider(CommandState.MY_STATE);
		commandStateService.toogleEnabled();
		return null;
	}

}

		

Add both commands to the menu.

Now use the state provided by your ISourceProvider in your declaration of your menu.

This looks in plugin.xml like the following.

			
<extension
         point="org.eclipse.ui.menus">
      <menuContribution
            locationURI="menu:org.eclipse.ui.main.menu">
         <command
               commandId="de.vogella.rcp.commands.sourceprovider.command1"
               label="Command1"
               style="push">
            <visibleWhen
                  checkEnabled="false">
               <with
                     variable="de.vogella.rcp.commands.sourceprovider.active">
                  <equals
                        value="ENABLED">
                  </equals>
               </with>
            </visibleWhen>
         </command>
         <command
               commandId="de.vogella.rcp.commands.sourceprovider.command2"
               label="Command2"
               style="push">
         </command>
      </menuContribution>
</extension>
		

If you now start your application can select the second command the first command will not be available anymore. If you press it again the first command will be displayed again.

10. Using parameters in commands

You can also define parameters in commands. Create project "de.vogella.rcp.commands.parameterfirst" using the "Hello RCP" template.

Create a command with the id "de.vogella.rcp.commands.parameterfirst.helloName" and a default handler "de.vogella.rcp.commands.parameterfirst.handler.HelloName".

Right click on your command, select New -> commandParameter

Use the following id for the parameter "de.vogella.rcp.commands.parameterfirst.commandParameter1"

In the handler you have to evaluate the parameter.

			
package de.vogella.rcp.commands.parameterfirst.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 HelloName extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String name = event
				.getParameter("de.vogella.rcp.commands.parameterfirst.commandParameter1");
		MessageDialog.openInformation(HandlerUtil.getActiveShell(event),
				"Hello", "Hello " + name);
		return null;
	}
}

		

Add this command to the menu. On the command, right click and select New -> Parameter

As name maintain the name of the parameter, pass as value the value you want to use in your handler.

Add the same command again to the menu and pass another parameter.

If you run your application and select the menu entry the value should be used in the message box.

11. Defining commands at runtime

You can create commands at runtime. Create 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.

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.

12. Thank you

Thank you for practicing with this tutorial.

I maintain this tutorial in my private time. If you like the information please help me by using flattr or donating or by recommending this tutorial to other people.

Flattr this

13. Questions and Discussion

Before posting questions, please see the vogella FAQ . If you have questions or find an error in this article please use the www.vogella.de Google Group . I have created a short list how to create good questions which might also help you. .

14. Links and Literature

14.1. Source Code

Source Code of Examples

14.2. Eclipse Commands Resources

http://wiki.eclipse.org/Platform_Command_Framework Command Framework wiki

http://wiki.eclipse.org/Command_Core_Expressions Commands Core Expressions

http://blog.eclipse-tips.com/2009/03/commands-part-6-toggle-radio-menu.html Blog series about Eclipse Command from Prakash G.R.

http://hermanlintvelt.blogspot.com/2009/06/eclipse-rcp-commands-part-3-visiblewhen.html Blog series about Eclipse Command from Herman Lintvelt