我正在开发一个JavaFX 2.2项目,想要对TreeItem的鼠标(双击)点击事件进行自定义处理。使用treeview.setOnMouseClicked可以在没有错误的情况下触发我的代码,但问题是每次鼠标双击时,TreeItem都会在展开和折叠之间切换。我想这是默认行为,但我该如何禁用它?
我正在开发一个JavaFX 2.2项目,想要对TreeItem的鼠标(双击)点击事件进行自定义处理。使用treeview.setOnMouseClicked可以在没有错误的情况下触发我的代码,但问题是每次鼠标双击时,TreeItem都会在展开和折叠之间切换。我想这是默认行为,但我该如何禁用它?
我曾经遇到同样的问题,但是使用 EventDispatcher
很快就解决了。
class TreeMouseEventDispatcher implements EventDispatcher {
private final EventDispatcher originalDispatcher;
public TreeMouseEventDispatcher(EventDispatcher originalDispatcher) {
this.originalDispatcher = originalDispatcher;
}
@Override
public Event dispatchEvent(Event event, EventDispatchChain tail) {
if (event instanceof MouseEvent) {
if (((MouseEvent) event).getButton() == MouseButton.PRIMARY
&& ((MouseEvent) event).getClickCount() >= 2) {
if (!event.isConsumed()) {
// Implement your double-click behavior here, even your
// MouseEvent handlers will be ignored, i.e., the event consumed!
}
event.consume();
}
}
return originalDispatcher.dispatchEvent(event, tail);
}
}
然后为TreeCell
使用TreeMouseEventDispatcher
:
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));
}
}
};
}
}
node.addEventHandler(MouseEvent.ANY, event -> {
if (event.getClickCount() == 2 && event.getButton().equals(MouseButton.PRIMARY)) {
if (event.getEventType().equals(MouseEvent.MOUSE_CLICKED)) {
System.out.println("hello"); // perform some action
}
event.consume();
}
});