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

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

本文介绍了使用JavaFX处理任何地方的鼠标事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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());
}
});

按钮按钮= new Button(click here);
root.getChildren()。add(button);

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

如果我点击空白处的任何地方, EventHandler 调用 handle()方法,但如果我点击按钮 handle()方法未被调用。在我的应用程序中有许多按钮和其他交互式元素,所以我需要一种方法来捕获这些元素的点击,而无需为每个元素手动添加一个新的处理程序。

解决方案

您可以使用。在事件被任何子控件使用之前,这将被调用。以下是事件过滤器的代码如何。

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


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();
}

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.

解决方案

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处理任何地方的鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:14