Context menu for TreeViewer based on selected node - SWT

前端 未结 4 1151
逝去的感伤
逝去的感伤 2020-12-31 13:51

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

4条回答
  •  借酒劲吻你
    2020-12-31 14:37

    Thats the way I do it:

    MenuManager menuMgr = new MenuManager();
    
            Menu menu = menuMgr.createContextMenu(viewer.getControl());
            menuMgr.addMenuListener(new IMenuListener() {
                @Override
                public void menuAboutToShow(IMenuManager manager) {
                    // IWorkbench wb = PlatformUI.getWorkbench();
                    // IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
                    if (viewer.getSelection().isEmpty()) {
                        return;
                    }
    
                    if (viewer.getSelection() instanceof IStructuredSelection) {
                        IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
                        Node object = (Node)selection.getFirstElement();
    
                        if (object.getModel() instanceof NodeA) {
                            manager.add(new Action();
                        } else if (object.getModel() instanceof NodeB) {
    
                            manager.add(new OtherAction());
    
                        }
                    }
                }
            });
            menuMgr.setRemoveAllWhenShown(true);
            viewer.getControl().setMenu(menu);
    

    I hope this helps ;)

    It is important to set removeAllWhenShown property of menu manager to false, in order to hide all the other nodes actions ;)

提交回复
热议问题