How to get X,Y coordinates of an image in a JLabel

2019-09-02 13:14发布

I have an image of a map placed as the icon of a JLabel. I am using following code to get the X,Y coordinates of the location where the mouse is clicked. I have put this code in the MouseClick event of the JLabel.

Point point = MouseInfo.getPointerInfo().getLocation();

double X = point.getX();
double Y = point.getY();

but the coordinates depend on the location of the JFrame form. If the form is moved the coordinates change.

Is there anyway I can freeze the JFrame? Or Is there anyway I can get a corner of the image as 0,0 and get the other coordinates relative to that? (So I can calculate the actual coordinates)

1条回答
【Aperson】
2楼-- · 2019-09-02 13:36

getLocation returns the mouse co-ordinates relative to the screen. Use the co-ordinates from the MouseEvent instead

label.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
         double x = e.getX();
         double y = e.getY();
         ...
    }
});
查看更多
登录 后发表回答