Handle mouse event anywhere with JavaFX(使用 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()
方法,但如果我点击 button
,EventHandler
code>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());
}
});
这篇关于使用 JavaFX 在任何地方处理鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JavaFX 在任何地方处理鼠标事件


基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01