Reputation: 407
I need to create a popup Menu for a Tree in Java SWT. But the menu should only pop up when no items are selected (when I click on a blank space of the TreeViewer). If I now select an item of the tree, I can't deselect it again. The TreeViewer is inside a 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.
Any ideas of how to remove an item selection when a blank space is (right-) clicked?
Upvotes: 1
Views: 6367
Reputation: 925
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.
Upvotes: 2
Reputation: 328556
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();
Upvotes: 5