要实现在GEF中被选中图形上的右键菜单,每个action完成如下三项工作:
<!--[if !supportLists]-->1、 <!--[endif]-->action类定义,一般情况的action都会在选中图形后操作,所以,一般都会继承自org.eclipse.gef.ui.actions.SelectionAction
import org.eclipse.gef.ui.actions.SelectionAction; import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeEditPart; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import dbdesigner.diagram.edit.parts.TableEditPart; public class TableProAction extends SelectionAction{ private IWorkbenchPart part; public TableProAction(IWorkbenchPart part) { super(part); setId("tablePro"); setText("属性"); this.part=part; } @Override public void run() { super.run(); IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); TableEditPart tableEditPart = (TableEditPart) getSelectedObjects().get(0); TableProDialog tp = new TableProDialog(workbenchWindow.getShell(),tableEditPart); tp.open(); } @Override protected boolean calculateEnabled() { if (getSelectedObjects().size() == 1 && (getSelectedObjects().get(0) instanceof ShapeEditPart)) { ShapeEditPart part = (ShapeEditPart) getSelectedObjects().get(0); if(part instanceof TableEditPart) return true; } return false; } }
<!--[if !supportLists]-->2、 <!--[endif]-->在DbdesignerDiagramEditor的createActions中将上述action注册到ActionRegistry,并设定和selectionaction的关系,这个类的是GEF生成的代码,只需要修改以下两个地方
prot protected void configureGraphicalViewer() { super.configureGraphicalViewer(); IDiagramGraphicalViewer viewer = getDiagramGraphicalViewer(); // configure the context menu provider ContextMenuProvider cmProvider = new MyDiagramContextMenuProvider(viewer, getActionRegistry()); viewer.setContextMenu(cmProvider); getSite().registerContextMenu(cmProvider, viewer); } /** * Create the actions */ protected void createActions() { // Create the actions super.createActions(); ActionRegistry ar = getActionRegistry(); //一组继承自selectionaction的action IAction[] actions = new IAction[] { new TableProAction(this) // 编辑属性 }; for (IAction a : actions) { ar.registerAction(a); getSelectionActions().add(a.getId()); } }
<!--[if !supportLists]-->3、 <!--[endif]-->在新增一个MyDiagramContextMenuProvider类,注册到右键菜单
public class MyDiagramContextMenuProvider extends ContextMenuProvider{ /** The editor's action registry. */ private ActionRegistry actionRegistry; public MyDiagramContextMenuProvider(EditPartViewer viewer, ActionRegistry registry) { super(viewer); if (registry == null) { throw new IllegalArgumentException(); } actionRegistry = registry; } public void buildContextMenu(IMenuManager menu) { //添加用户自定义菜单项 menu.add(getAction("tablePro")); } // 过滤不需要的上下文菜单 public IContributionItem[] getItems() { IContributionItem[] ic = super.getItems(); filterSystemPopMenu(ic); return ic; } private void filterSystemPopMenu(IContributionItem[] ic) { for (int i=0;i