【问题标题】:Mouse Event on stackPane JavaFX without children没有孩子的stackPane JavaFX上的鼠标事件
【发布时间】:2019-11-09 00:02:15
【问题描述】:

您好,当鼠标单击堆栈窗格(父亲)时,我试图取消选择列表视图项。我尝试了这段代码,但是当用户单击按钮(Stackpane 的子项)时,无论如何都会触发该事件:

stackPane.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                listVisits.getSelectionModel().clearSelection();
            }
        });

如何只触发堆栈窗格鼠标事件点击?

【问题讨论】:

标签: listview javafx event-handling mouseevent


【解决方案1】:

您不需要MOUSE_PRESSED。替换为MOUSE_CLICKED

stackPane.setOnMouseClicked(event -> {
     listVisits.getSelectionModel().clearSelection();
});

【讨论】:

  • 我尝试将MOUSE_PRESSED 替换为MOUSE_CLICKED,但在单击listview 行后仍保持选中状态
  • 这并不能真正解决问题。 StackPane 的任何子级不使用单击事件仍会清除选择...
【解决方案2】:

您可以使用MouseEventpickResult 属性轻松区分这些情况。请注意,在这种情况下,不需要使用允许使用事件处理程序的事件过滤器,这会导致代码更短(当然,除非您需要将其设置为另一个值)。

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多