user3726374
user3726374

Reputation: 605

Jface TreeViewer add right click menu, depending on clicked node

There is a good thread on how to correctly hook up a right-click menu to a Jface TreeViewer depending on the selected item.

I would like to show the right click menu depending on: if the right-click was on a node or into "empty space". The problem is that TreeViewer does not automatically clear the selection if you click into empty space. Is there any clean way how to achieve this?

My current approach would be to simply hook up a MouseListener to the tree with the following mouseDown method:

@Override
public void mouseDown(MouseEvent e) {
    TreeItem item = treeViewer.getTree().getItem(new Point(e.x, e.y));
    if (item == null) {
        treeViewer.getTree().deselectAll();
    }
}

This seems to work quite well. What do you think of this?

Upvotes: 0

Views: 2215

Answers (2)

Abhishek2k6
Abhishek2k6

Reputation: 435

How to add popup menu to your SWT/JFace TreeViewer
Hi, in your applications main class (that extends ApplicationWindow) in protected Control createContents(Composite parent) method you should add code like this:
//Author: Darius Kucinskas (c) 2008-2009
//Email: d[dot]kucinskas[eta]gmail[dot]com
//Blog: http://blog-of-darius.blogspot.com/
//License: GPL

// Create the popup menu
  MenuManager menuMgr = new MenuManager();
  Menu menu = menuMgr.createContextMenu(mTreeViewer.getControl());
  menuMgr.addMenuListener(new IMenuListener() {
    @Override
    public void menuAboutToShow(IMenuManager manager) {
      if(mTreeViewer.getSelection().isEmpty()) {
        return;
      }

      if(mTreeViewer.getSelection() instanceof IStructuredSelection) {
        IStructuredSelection selection = (IStructuredSelection)mTreeViewer.getSelection();
        DatabaseModelObject object = (DatabaseModelObject)selection.getFirstElement();

        if (object.getType() == DATABASE_OBJECT_TYPE.TABLE){
          manager.add(new ShowTableDataAction(SWTApp.this));
        }
      }
    }
  });

  menuMgr.setRemoveAllWhenShown(true);
  mTreeViewer.getControl().setMenu(menu);
DatabaseModelObject - is class from my problem domain (specific to my program). mTreeViewer - is object of TreeViewer class (JFace). Thanks, have a nice day!

Upvotes: 0

Baz
Baz

Reputation: 36904

Ok, I found a dirty workaround. So if you really want to do it, here is a possible solution:

final Tree tree = viewer.getTree();

final Menu menu = new Menu(tree);
tree.setMenu(menu);
menu.addMenuListener(new MenuAdapter()
{
    @Override
    public void menuShown(MenuEvent e)
    {
        Point point = tree.toControl(Display.getDefault().getCursorLocation());
        boolean found = false;
        for (TreeItem item : tree.getItems())
        {
            for (int i = 0; i < tree.getColumnCount(); i++)
                if (item.getBounds(i).contains(point))
                    found = true;
        }

        System.out.println(found);
    }
});

Upvotes: 0

Related Questions