使用 JavaFX 在任何地方处理鼠标事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18597939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handle mouse event anywhere with JavaFX
提问by Sam De Meyer
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:
我有一个 JavaFX 应用程序,我想为场景中的任意位置的鼠标单击添加一个事件处理程序。以下方法可以正常工作,但不完全是我想要的方式。下面是一个示例来说明问题:
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();
}
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.
如果单击空白处的任意位置,则EventHandler
调用该handle()
方法,但如果单击button
,handle()
则不会调用该方法。我的应用程序中有许多按钮和其他交互式元素,因此我需要一种方法来捕获对这些元素的点击,而不必为每个元素手动添加新的处理程序。
采纳答案by Brian Blonski
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.
您可以使用addEventFilter()向场景添加事件过滤器。这将在任何子控件使用该事件之前调用。下面是事件过滤器的代码。
scene.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
System.out.println("mouse click detected! " + mouseEvent.getSource());
}
});