[英]Handle mouse event anywhere with JavaFX
I have a JavaFX application, and I would like to add an event handler for a mouse click anywhere within the scene. 我有一个JavaFX应用程序,我想在场景中的任何地方添加一个鼠标单击的事件处理程序。 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();
}
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. 如果我单击空白处的任何位置, EventHandler
调用handle()
方法,但如果单击该button
,则不会调用handle()
方法。 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. 我的应用程序中有许多按钮和其他交互元素,因此我需要一种方法来捕获这些元素的点击,而无需为每个元素手动添加新的处理程序。
You can add an event filter to the scene with addEventFilter() . 您可以使用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());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.