32

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.

SpaceCore186
5841 gold badge8 silver badges22 bronze badges
asked Sep 3, 2013 at 17:15
0

1 Answer 1

60

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());
 }
});
answered Sep 3, 2013 at 20:21
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.