如何为jface treeviewer创建鼠标右键菜单

时间:2014-12-08 05:55:13

标签: java jface e4 treeviewer

我使用JFace创建了TreeViewer,但现在我必须向节点添加一个右键单击侦听器。右键单击完成后,必须显示如下菜单:

  1. 做点什么
  2. 什么都不做
  3. 删除
  4. 我试图按照以下方式执行此操作,但它会抛出空指针异常。

    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);
    

1 个答案:

答案 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