Alex Rivera | Logout

Context menu for TreeViewer based on selected node - SWT

Asked 2011-06-01T21:12:33.737
9

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

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 ?
                        }
                    }

                }
            }   
    );

On the else branch I tried to call dispose(),removeAll() on the MenuManager...nothing works!

Any help is appreciated, thanks.

Edit
Report

1 Answer

8

Just use single Menu Manager. Do not make Menu Manager dynamically.

in theory, It's possible you tried, but it's inefficient and it's not general way.

Just make a Menu Manager and add all actions which you needs.

when selection has been changed, call Action#setVisible(true|false)to hide or show menu items. You can also use Action#setEnable to enable/disable menu item.

ps. Menu Manager is not a menu GUI(likes TreeViewer is a not tree)

It contributes Actions(business logic) to Menu(SWT). And It also manage visibility and enablement. We call this Contribution Manager. We can create a SWT menu very easy with this. (even we don't know about SWT, we just have to know only our business logic:Action) It's fundamental idea in JFace.

When you add an action into manu manager, action will be wrapped with ActionContributionItem. It hooks action's state to update UI(visibility, enablement for menu, button, toolbar and so on). It also hooks UI to launch action when it pressed.

If you are new to eclipse, It is easy to confuse role of SWT and JFace.

answered 2011-06-02T00:53:04.897

Your Answer