简体   繁体   English

Java SWT:删除对树项的选择

[英]Java SWT: remove selection of a tree item


I need to create a popup Menu for a Tree in Java SWT. 我需要在Java SWT中为树创建弹出菜单。 But the menu should only pop up when no items are selected (when I click on a blank space of the TreeViewer). 但是,仅当未选择任何项目时(当我单击TreeViewer的空白区域时),才应弹出菜单。 If I now select an item of the tree, I can't deselect it again. 如果现在选择树的一个项目,则无法再次取消选择它。 The TreeViewer is inside a Composite. TreeViewer在Composite内部。
My first idea was to add a MouseListener to check if no of the Items are selected and call deselectAll() , but event.getSource() only returns the tree. 我的第一个想法是添加一个MouseListener来检查是否未选择任何Items并调用deselectAll() ,但是event.getSource()仅返回树。
Any ideas of how to remove an item selection when a blank space is (right-) clicked? 单击(右)空白时如何删除项目选择的任何想法?

Often, you can deselect by Ctlr-clicking the item. 通常,您可以通过Ctlr单击该项目来取消选择。

Another option is to register a listener for mouse clicks, and use the event location to locate the tree item. 另一种选择是为鼠标单击注册侦听器,并使用事件位置找到树项。 If this returns null, you can call deselectAll() . 如果返回null,则可以调用deselectAll()

But how can you get the TreeViewer from the Tree ? 但是,如何从Tree获取TreeViewer Simple: Store the reference in the data property of the tree. 简单:将引用存储在树的data属性中。 Then you can use this code in your event handler: 然后,您可以在事件处理程序中使用以下代码:

TreeViewer view = (TreeViewer) event.getSource().getData();

event.getSource().getLocation() just tells you the current location of the Tree widget in the parent coordinate system, that's why it's always the same. event.getSource()。getLocation()只是告诉您Tree窗口小部件在父坐标系中的当前位置,这就是为什么它总是相同的原因。 You need to get the click coordinates from the MouseEvent instead. 您需要改为从MouseEvent获取点击坐标。 It has x and y, which should be the click coordinates. 它有x和y,应该是点击坐标。

To sum up: 总结一下:

Tree tree = (Tree) event.getSource();
if (tree.getItem(new Point(event.x, event.y)) != null)
    // an item was clicked.
else
    // no item was clicked.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM