Can I get different mouse-click events from a TreeViewItem depending on the user clicks on the icon or on the text label? The icon is not the collapse image of the tree.
Asked
Active
Viewed 506 times
1 Answers
0
According to Disable TreeItem's default expand/collapse on double click JavaFX 2.2 I have changed the constructor of the TreeMouseEventDispatcher:
class TreeMouseEventDispatcher implements EventDispatcher {
private final EventDispatcher originalDispatcher;
private final TreeCell<?> cell;
public TreeMouseEventDispatcher(EventDispatcher originalDispatcher, TreeCell<?> cell) {
this.originalDispatcher = originalDispatcher;
this.cell = cell;
}
private boolean isMouseEventOnGraphic(Node icon, Point2D coord) {
if (icon == null) {
return false;
}
return icon.localToScene(icon.getBoundsInLocal()).contains(coord);
}
@Override
public Event dispatchEvent(Event event, EventDispatchChain tail) {
if (event instanceof MouseEvent) {
MouseEvent mouseEvent = (MouseEvent) event;
if (mouseEvent.getButton() == MouseButton.PRIMARY
&& mouseEvent.getClickCount() >= 2) {
if (!mouseEvent.isConsumed()) {
if (isMouseEventOnGraphic(cell.getGraphic(), new Point2D(mouseEvent.getSceneX(), mouseEvent.getSceneY()))) {
// action for double click on graphic
} else {
// action for double click on all other elements of
// the TreeCell (like text, text gap, disclosure node)
}
}
event.consume();
}
}
return originalDispatcher.dispatchEvent(event, tail);
}
}
and then use this TreeMouseEventDispatcher
for the TreeCell
:
treeView.setCellFactory(new Callback<TreeView<T>, TreeCell<T>>() {
@Override
public TreeCell<T> call(TreeView<T> param) {
return new TreeCell<T>() {
@Override
protected void updateItem(T item, boolean empty) {
if (item != null && !empty) {
EventDispatcher originalDispatcher = getEventDispatcher();
setEventDispatcher(new TreeMouseEventDispatcher(originalDispatcher, this));
}
}
};
}
}