我使用JFace创建了TreeViewer
,但现在我必须向节点添加一个右键单击侦听器。右键单击完成后,必须显示如下菜单:
我试图按照以下方式执行此操作,但它会抛出空指针异常。
MenuManager menuMgr = new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager menuManager) {
IContributionManager menu = null;
MenuItem[] items = (MenuItem[]) menu.getItems();
for (int i = 0; i < items.length; i++)
items[i].dispose();
MenuItem itemCollectionFolder = new MenuItem((Menu) menu, SWT.NONE);
itemCollectionFolder.setText("Add Something" );
MenuItem itemNewTestCase = new MenuItem((Menu) menu, SWT.NONE);
itemNewTestCase.setText("Do Nothing" );
}
});
Control tree = treeViewer.getControl();
Menu menu = menuMgr.createContextMenu(tree);
tree.setMenu(menu);
答案 0 :(得分:7)
试试这个,别忘了打电话: createContextMenu(观看者);
/**
* Creates the context menu
*
* @param viewer
*/
protected void createContextMenu(Viewer viewer) {
MenuManager contextMenu = new MenuManager("#ViewerMenu"); //$NON-NLS-1$
contextMenu.setRemoveAllWhenShown(true);
contextMenu.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager mgr) {
fillContextMenu(mgr);
}
});
Menu menu = contextMenu.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
}
/**
* Fill dynamic context menu
*
* @param contextMenu
*/
protected void fillContextMenu(IMenuManager contextMenu) {
contextMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
contextMenu.add(new Action("Do Something") {
@Override
public void run() {
// implement this
}
});
contextMenu.add(new Action("Do Nothing") {
@Override
public void run() {
// don't do anything here
}
});
contextMenu.add(new Action("Delete") {
@Override
public void run() {
// implement this
}
});
}
要获取树视图的选定元素,请执行以下操作:
IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
selection.getFirstElement();
selection.toList(); // or if you handle multi selection