Search code examples
javajavafxshapesgeometryscene

Remove Shape without knowing its reference (javafx)


I would like to create a circle at my cursor with a left click ( this works ) and delete the circle that is below the cursor with a right click ( this doesnt work ).

My Problem is that I dont know how to access the circle without its reference ( its name ), because all circles are created during runtime. I ve heard that generics could solve my problem but i dont really understand them. If there is another way please let me know.

Here is the code:

public class circle extends Application {

@Override
public void start(Stage stage) {

    Group root = new Group();
    Scene scene = new Scene(root, 600, 600, Color.ALICEBLUE);

    scene.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {

            if(event.getButton() == MouseButton.PRIMARY) {
                root.getChildren().add(new Circle(event.getSceneX(), event.getSceneY(), 10, Color.DARKCYAN));
            }               

            // Does not work. It should delete the circle below the cursor
            if(event.getButton() == MouseButton.SECONDARY) {
                root.getChildren().remove((int)event.getSceneX(), (int)event.getSceneX());
            }
        }
    });

    stage.setScene(scene);
    stage.setTitle("Thx for helping me :)");
    stage.show();
}

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

If i misunderstood the term "reference" i m sorry. I think its the name you give an object as you create it. ( Circle "reference" = new Circle(); )

Thx for helping me!


Solution

  • Register the listener for the right click with the circle directly:

    scene.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
    
            if(event.getButton() == MouseButton.PRIMARY) {
                Circle circle = new Circle(event.getSceneX(), event.getSceneY(), 10, Color.DARKCYAN);
                circle.setOnMouseClicked(e  -> {
                    if (e.getButton() == MouseButton.SECONDARY) {
                        root.getChildren().remove(circle);
                    }
                });
                root.getChildren().add(circle);
            }               
    
    
        }
    });