您好,当我单击堆栈窗格(父亲)时,我试图取消选择列表视图项。我尝试使用此代码,但是当用户单击按钮(Stackpane的子代)时,无论如何都会触发该事件:
stackPane.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
listVisits.getSelectionModel().clearSelection();
}
});
我如何仅触发堆栈窗格鼠标事件单击?
您不需要MOUSE_PRESSED
。替换为MOUSE_CLICKED
stackPane.setOnMouseClicked(event -> {
listVisits.getSelectionModel().clearSelection();
});
您可以使用pickResult
的MouseEvent
属性轻松区分情况。请注意,在这种情况下,无需使用事件过滤器就可以使用事件处理程序,这会导致代码缩短(当然,除非需要将其设置为另一个值)。
stackPane.setOnMousePressed(evt -> {
// only update selection, if the cursor doesn't hover a child
if (evt.getPickResult().getIntersectedNode() == stackPane) {
listVisits.getSelectionModel().clearSelection();
evt.consume(); // don't pass the event to event handlers of ancestors (desired ?)
}
});
请注意,如果您只想排除某些子项将事件传递给StackPane
而不是全部,则可以使用事件处理程序来消耗某些子项的事件。如果这样做,则不再需要检查pickResult
:
eventBlockingChild.setOnMousePressed(MouseEvent::consume);