Max Smashdidypwned Lay
Max Smashdidypwned Lay

Reputation: 385

JavaFX: Get the x and y pixel coordinates clicked on an ImageView

I have an ImageView inside a ScrollPane. I can get the mouse click event by adding a listener to the ScrollPane. However, I want to get the x and y coordinates of the pixel on the image that was clicked.

To make it even more complicated, the image can be zoomed in and out on, but I can probably figure that out once I have some idea of what I am doing.

Upvotes: 1

Views: 8302

Answers (1)

James_D
James_D

Reputation: 209418

Add the mouse listener to the ImageView instead of to the ScrollPane.

Here is a simple example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class ClickOnScrollingImage extends Application {

    private static final String IMAGE_URL = "https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/crop_p_color2_enhanced_release_small.png?itok=5BtHNey_" ;


    @Override
    public void start(Stage primaryStage) {
        ScrollPane scroller = new ScrollPane();
        ImageView imageView = new ImageView(IMAGE_URL);
        scroller.setContent(imageView);

        // the following line allows detection of clicks on transparent
        // parts of the image:
        imageView.setPickOnBounds(true);

        imageView.setOnMouseClicked(e -> {
            System.out.println("["+e.getX()+", "+e.getY()+"]");
        });
        Scene scene = new Scene(scroller, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Upvotes: 6

Related Questions