問題描述
我有一個 JavaFX 應(yīng)用程序,我想為場景中任意位置的鼠標單擊添加一個事件處理程序.以下方法工作正常,但不完全按照我想要的方式.下面是一個示例來說明問題:
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();
}
如果我點擊空白區(qū)域的任意位置,EventHandler
會調(diào)用 handle()
方法,但如果我點擊 button
,EventHandler
code>handle() 方法沒有被調(diào)用.我的應(yīng)用程序中有許多按鈕和其他交互元素,因此我需要一種方法來捕獲對這些元素的點擊,而不必為每個元素手動添加新的處理程序.
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().這將在任何子控件使用事件之前調(diào)用.下面是事件過濾器的代碼.
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());
}
});
這篇關(guān)于使用 JavaFX 在任何地方處理鼠標事件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!