基于所选节点的 TreeViewer 上下文菜单 - SWT
我需要在 Eclipse 插件项目中为 TreeViewer 创建一个上下文菜单.但是,菜单不应包含常量项,它们应根据所选节点的类型而有所不同.例如,我的 treeViewer 具有以下层次结构:
I need to create a context menu for a TreeViewer in an Eclipse plugin project. But, the menu should not contain constant items, they should vary depending on the type of the node that is selected. For example, my treeViewer has the following hierarchy:
Node A
|
--Node B
|
--Node C
对于节点 A - 我想显示一个带有操作的菜单,但对于节点 B 和 C,我不想显示任何内容(无菜单).I managed to create the menu for node A, but then I can't get rid of it when some other type of node is selected.我的代码如下:
For node A - I want to show a menu with an action, but for nodes B and C I don't want to show anything (no menu). I managed to create the menu for node A, but then I can't get rid of it when some other type of node is selected. My code looks like:
treeViewer.addSelectionChangedListener(
new ISelectionChangedListener(){
public void selectionChanged(SelectionChangedEvent event) {
if(event.getSelection() instanceof IStructuredSelection) {
IStructuredSelection selection = (IStructuredSelection)event.getSelection();
Object o = selection.getFirstElement();
MenuManager menuMgr = new MenuManager();
if (o instanceof NodeA){
Menu menu = menuMgr.createContextMenu(treeViewer.getControl());
treeViewer.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, treeViewer);
menuMgr.add(new SomeAction());
}else {
//what ?
}
}
}
}
);
在 else 分支上,我尝试在 MenuManager 上调用 dispose()
,removeAll()
...没有任何效果!
On the else branch I tried to call dispose()
,removeAll()
on the MenuManager...nothing works!
感谢您的帮助.
推荐答案
正如@jeeeyul 提到的,您应该只创建一个 MenuManager 以在您的视图中使用.
As @jeeeyul mentioned, you should only create one MenuManager to use within your view.
您可以使用 New>Plug-in Project 和视图模板在使用查看器的视图中获取上下文菜单的示例,但基本上在您的 createPartControl(Composite)
方法中,您将挂钩启动你的上下文管理器.
You can use New>Plug-in Project and the view template to get an example of a context menu in a view using a viewer, but basically in your createPartControl(Composite)
method you would hook up your context manager.
MenuManager menuMgr = new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
SampleView.this.fillContextMenu(manager);
}
});
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, viewer);
您的 fillContextMenu(MenuManager)
方法将可以访问您的查看器,因此您可以从中获取当前选择.您可以添加任何您想要的操作,甚至在使用当前选择更新它们后重新添加操作.
Your fillContextMenu(MenuManager)
method will have access to your viewer, so you can get the current selection from that. You can add whatever actions you want, even re-add actions after updating them with the current selection.
registerContextMenu(*)
调用允许 org.eclipse.ui.popupMenus 和 org.eclipse.ui.menus 等扩展点向上下文菜单添加项目.
The registerContextMenu(*)
call allows extension points like org.eclipse.ui.popupMenus and org.eclipse.ui.menus to contribute items to your context menu.
相关文章