Events for two overlay shapes

Viewed 40

My problem: I have a two overlay shapes, for example, two rectangles: A and B. When B overlay A rectangle.

I add setOnMouseMoved handlers for both and i see that events handles only by top figure.

Code example:

public class MainExample extends Application {
    @Override
    public void start(Stage stage) {
        stage.setMinWidth(700);
        stage.setMaxWidth(700);
        stage.setMinHeight(800);
        stage.setMaxHeight(800);

        StackPane root = new StackPane();

        var a = new Rectangle(300, 300, Color.BLUE);
        var b = new Rectangle(200, 200);

        root.getChildren().addAll(a, b);

        b.setOnMouseMoved(mouseEvent -> {
            System.out.println("Mouse moved b!");
        });

        a.setOnMouseMoved(mouseEvent -> System.out.println("Mouse moved a!"));

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

What i want:

In the area of overlapping figures mouse moved events handles both of figures: A and B.

Thanx everyone for help!

1 Answers

I replace both mouse events to just one in stackpane node . The event checks if mouse coords is inside in both bounds (node a and node b) . When the mouse is in an area that intersetcs both rectangles the event wil thrigger both print statments

public class MainExample extends Application {
    @Override
    public void start(Stage stage) {
        stage.setMinWidth(700);
        stage.setMaxWidth(700);
        stage.setMinHeight(800);
        stage.setMaxHeight(800);

        StackPane root = new StackPane();

        var a = new Rectangle(300, 300, Color.BLUE);
        
        var b = new Rectangle(200, 200);
        

        root.getChildren().addAll(a, b);

        root.setOnMouseMoved(mouseEvent -> {
            
            if(b.getBoundsInParent().contains(mouseEvent.getSceneX(),mouseEvent.getSceneY())){
            System.out.println("Mouse moved b!");}
            if(a.getBoundsInParent().contains(mouseEvent.getSceneX(),mouseEvent.getSceneY())){
            System.out.println("Mouse moved a!");}
        });

        

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}
Related