使用 JavaFX 在任何地方处理鼠标事件

2022-01-15 00:00:00 mouseevent event-handling java javafx

我有一个 JavaFX 应用程序,我想为场景中任意位置的鼠标单击添加一个事件处理程序.以下方法工作正常,但不完全按照我想要的方式.下面是一个示例来说明问题:

I have a JavaFX application, and I would like to add an event handler for a mouse click anywhere within the scene. The following approach works ok, but not exactly in the way I want to. Here is a sample to illustrate the problem:

public void start(Stage primaryStage) {
    root = new AnchorPane();
    scene = new Scene(root,500,200);
    scene.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            System.out.println("mouse click detected! "+event.getSource());
        }
    });

    Button button = new Button("click here");
    root.getChildren().add(button);

    primaryStage.setScene(scene);
    primaryStage.show();
}

如果我点击空白区域的任意位置,EventHandler 会调用 handle() 方法,但如果我点击 buttonEventHandlercode>handle() 方法没有被调用.我的应用程序中有许多按钮和其他交互元素,因此我需要一种方法来捕获对这些元素的点击,而不必为每个元素手动添加新的处理程序.

If I click anywhere in empty space, the EventHandler invokes the handle() method, but if i click the button, the handle() method is not invoked. There are many buttons and other interactive elements in my application, so I need an approach to catch clicks on those elements as well without having to manually add a new handler for every single element.

推荐答案

您可以使用 addEventFilter().这将在任何子控件使用事件之前调用.下面是事件过滤器的代码.

You can add an event filter to the scene with addEventFilter(). This will be called before the event is consumed by any child controls. Here's what the code for the event filter looks like.

scene.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent mouseEvent) {
        System.out.println("mouse click detected! " + mouseEvent.getSource());
    }
});

相关文章