How to get mouse pointer location relative to frame

╄→尐↘猪︶ㄣ 提交于 2020-01-14 02:52:12

问题


I want to get mouse location relative to the frame.

MouseInfo give me the absolute location.

How to get poisition relative to the frame? tahnks.


回答1:


Get the absolute location of the frame with getLocationOnScreen(), and then compute the relative distance.




回答2:


First, walk up the tree from your current scope to the top (that will be the frame):

Container container = this.getParent();
Container previous = container;
while (container != null)
{
    previous = container;
    container = container.getParent();
}

previous is the top container

if (previous instanceof JFrame)
{
    Point p = ((JFrame)previous).getMousePosition();
    System.out.println(p); // or do what you need to with p
}



回答3:


To calculate the location of the mouse relative to the frame, you must subtract the absolute location of the mouse from the location of the frame, thus cancelling the extraneous points from the upper left corner of the frame to the upper left corner of the screen.

To get location of mouse relative to the frame as a Point:

public Point getLocationRelativeTo() {
    int x = frame.getX() - MouseInfo.getPointerInfo().getLocation().x;
    int y = frame.getY() - MouseInfo.getPointerInfo().getLocation().y;
    return new Point(x, y);
}

To get the x as an int:

public int getXRelativeTo() {
    int x = frame.getX() - MouseInfo.getPointerInfo().getLocation().x;
    return x;
}

To get the y as an int:

public int getXRelativeTo() {
    int y = frame.getY() - MouseInfo.getPointerInfo().getLocation().y;
    return y;
}

I hope the helped. :)

For more info, visit http://docs.oracle.com/javase/7/docs/api/java/awt/MouseInfo.html



来源:https://stackoverflow.com/questions/12700520/how-to-get-mouse-pointer-location-relative-to-frame

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