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

爷,独闯天下 提交于 2019-12-11 18:09:26

问题


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:


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


来源:https://stackoverflow.com/questions/19977589/how-to-get-x-y-coordinates-of-an-image-in-a-jlabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!