根据所选项目,如何正确地将右键菜单连接到Jface TreeViewer
,有一个good thread。
我想显示右键菜单,具体取决于:如果右键单击是在节点上还是在“空白空间”中。问题是如果单击空白空间,TreeViewer不会自动清除选择。有没有什么干净的方法来实现这个目标?
我目前的方法是使用以下mouseDown方法简单地将MouseListener
连接到树:
@Override
public void mouseDown(MouseEvent e) {
TreeItem item = treeViewer.getTree().getItem(new Point(e.x, e.y));
if (item == null) {
treeViewer.getTree().deselectAll();
}
}
这看起来效果很好。你怎么看待这个?
答案 0 :(得分:0)
好的,我找到了一个肮脏的解决方法。所以如果你真的想这样做,这是一个可能的解决方案:
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);
}
});
答案 1 :(得分:0)
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!