RSS

Search Engine

Wednesday, June 16, 2010

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

0 comments:

Post a Comment