javaswtjfacee4treeviewer

How to create a mouse rightclick menu for a jface treeviewer


I have created a TreeViewer using JFace, but now I have to add a right click listener to the nodes. When the right click is done it has to show a menu like:

  1. Do something
  2. Do Nothing
  3. Delete

I am trying to do this as follows, but it is throwing a null pointer exception.

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

Solution

  • Try this, don't forget to call: createContextMenu(viewer);

    /**
     * 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
            }
        });
    }
    

    To get the selected element of the treeviewer, do this:

    IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
    selection.getFirstElement();
    selection.toList(); // or if you handle multi selection