Amita Patil Amita Patil - 4 months ago 7
Java Question

How to detect whether the given point is in particular controls bound or not in JavaFX

I want to detect whether the given point is in my controls area/bound or not.
example - Point(100, 100) I want to know whether it is on my button or not?

Answer

Transform the point to the Node coordinate system and use Node.contains to check, if the point is actually inside the Node:

The following example checks every 500 ms, if the screen coordinates (100, 100) are in the Button's bounds

@Override
public void start(Stage primaryStage) {
    Button btn = new Button("Get (100, 100) in here");
    Point2D pt = new Point2D(100, 100);

    Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(0.5), evt ->
            System.out.println(
                   btn.contains(btn.screenToLocal(pt))
            )
    ));
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();

    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root, 200, 50);

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