您好,我试图取消选择列表视图项时,鼠标点击堆栈窗格(父亲)。我尝试了这段代码,但当用户单击按钮(Stackpane的子项)时,无论如何都会触发事件:
stackPane.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
listVisits.getSelectionModel().clearSelection();
}
});如何才能仅触发堆栈窗格鼠标事件单击?
发布于 2019-11-08 20:15:06
您不需要MOUSE_PRESSED。替换为MOUSE_CLICKED
stackPane.setOnMouseClicked(event -> {
listVisits.getSelectionModel().clearSelection();
});发布于 2019-11-08 23:54:50
您可以使用MouseEvent的pickResult属性轻松区分这两种情况。请注意,在这种情况下,不需要使用允许使用事件处理程序的事件过滤器,这会导致代码略短(当然,除非您需要将其设置为另一个值)。
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);https://stackoverflow.com/questions/58765897
复制相似问题