Abdul Subbooh Danyal
Abdul Subbooh Danyal

Reputation: 127

Add a spot on JavaFx ImageView

I want the spot on ImageView where users click. I am getting the coordinates where user click but how to add the spot on that point? Is it possible to add a spot on the specified coordinates? If yes how?

Upvotes: 1

Views: 367

Answers (1)

Shekhar Rai
Shekhar Rai

Reputation: 2058

You can use a Circle or other Shape for a spot. Add a new spot on every mouse click in the clicked position. Check this demo,

public class ImageViewSpotDemo extends Application {    
    @Override
    public void start(Stage primaryStage) {     
        Pane root = new Pane();

        ImageView image = new ImageView(new Image("file:src/path/image.png"));
        image.setOnMouseClicked(e -> {

            //A new spot
            Circle spot = new Circle(4);
            spot.setFill(Color.WHITE);
            spot.setCenterX(4.0f);
            spot.setCenterY(4.0f);

            double x = e.getSceneX() - 3;
            double y = e.getSceneY() - 3;

            spot.setLayoutX(x);
            spot.setLayoutY(y);

            root.getChildren().add(spot);
        });

        root.getChildren().add(image);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Note : Use the Pane layout as parent root for image-view and spots for positioning. Why? Check answer of @jewelsea on Explicitly positioning nodes in JavaFX.

Upvotes: 3

Related Questions