Java SWT: remove selection of a tree item
deselectAll()
, but event.getSource()
only returns the tree.
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.
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()
.
But how can you get the TreeViewer
from the Tree
? Simple: Store the reference in the data
property of the tree. 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. You need to get the click coordinates from the MouseEvent instead. It has x and y, which should be the click coordinates.
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.
精彩评论