Eclipse的Command应用教程(一)

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.

This article is based on Eclipse Helios (3.6).


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. Commands are defined via the extension point "org.eclipse.ui.commands". 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.

To use a command in your User Interface 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

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. Location URI's

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 content menu, e.g. right mouse click on an object n.a.


You can define the relative position of a command in this location URI 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 id "fileMenu" behind the menu entry with the id "oneEntry" use the locationURI of "menu:fileMenu?after=oneEntry".

1.3. Command Handler

The behavior of a command is defined via handlers. The handler is the class which will be executed once the command is called and must implement the interface "org.eclipse.core.commands.IHandler". "org.eclipse.core.commands.AbstractHandler" provides a default implementation for the IHandler interface.

IHandler defines the following important methods which can be implemented:

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

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

  • execute: Coding which performs the action

  • fireHandlerChanged: needs to be called if isEnabled is changed

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 cannot decide which one should be used and the command will not be enabled.

2.  Commands and menus

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

}

		

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

<script type="text/javascript"></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

3. Commands and toolbars

3.1. Overview

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

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

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 the class "Perspective" 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". ""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 example 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.  Advanced Commands

For more advanced usages of Eclipse Commands please see Eclipse Commands Advanced.

猜你喜欢

转载自bill-xing.iteye.com/blog/1180882