有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javajavafx:在ImageView上单击x和y像素坐标

我在滚动窗格中有一个ImageView。我可以通过向滚动窗格添加一个侦听器来获取鼠标单击事件。但是,我想得到点击图像上像素的x和y坐标

更复杂的是,图像可以放大和缩小,但一旦我对自己正在做的事情有了一些想法,我可能就会明白这一点


共 (1) 个答案

  1. # 1 楼答案

    将鼠标侦听器添加到ImageView而不是ScrollPane

    下面是一个简单的例子:

    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);
        }
    }