我可以从TreeViewItem获取不同的鼠标单击事件,具体取决于用户点击图标或文本标签吗?该图标不是树的折叠图像。
答案 0 :(得分:0)
根据Disable TreeItem's default expand/collapse on double click JavaFX 2.2,我更改了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);
}
}
然后将此TreeMouseEventDispatcher
用于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));
}
}
};
}
}