隐藏TreeViewer中的菜单项

时间:2011-11-08 20:57:49

标签: java eclipse-plugin jface

我试图从上下文(弹出菜单)隐藏/取消隐藏子菜单项(menumanager) 在树中选择/未选择特定节点时。

虽然setVisible方法按预期触发但它不起作用。

守则:

TreeViewer tViewer;

tViewer = new TreeViewer(parent, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);

tViewer.setLabelProvider(new WorkbenchLabelProvider());
tViewer.setContentProvider(new BaseWorkbenchContentProvider());
tViewer.setInput(viewFactory.getInstance().getRoot());      


final MenuManager menuMain = new MenuManager("Main",null);
menuMain.add(mActionClose);


MenuManager menuManager = new MenuManager("#PopupMenu", "contextMenu");
menuManager.add(menuMain);


menuManager.addMenuListener(new IMenuListener() {           
    public void menuAboutToShow(IMenuManager manager) {             

        //Get the selected node in tree
        IStructuredSelection selection = (IStructuredSelection) tViewer.getSelection();

        if (!selection.isEmpty()) { //If something selected
            NNodeBase ob = (NNodeBase) selection.getFirstElement(); //Get the base class of node                                    

            if (!(ob instanceof NTMModel)) {                        
                menuMain.setVisible(false);                     
            }
            else
                menuMain.setVisible(true);                      
        }
    }
});


Menu menu = menuManager.createContextMenu(tViewer.getControl());
tViewer.getControl().setMenu(menu);

1 个答案:

答案 0 :(得分:2)

您必须将管理器设置为在显示之前重新创建菜单:

menuManager.setRemoveAllWhenShown(true);

然后,在menuAboutToShow()中添加项目,测试您需要的条件:

if ((ob instanceof NTMModel)) {
    menuManager.add(mActionClose);
} else {
    // don't show the menu item
}

您不再需要menuMain