题
我想获得相对于框架的鼠标位置。
mouseinfo给我绝对位置。
如何获得相对于框架的盗用?tahnks。
解决方案
使用getLocationOnscreen()获取帧的绝对位置,然后计算相对距离。
其他提示
首先,从当前范围到顶部的树(这将是框架):
Container container = this.getParent();
Container previous = container;
while (container != null)
{
previous = container;
container = container.getParent();
}
.
上一个是顶部容器
if (previous instanceof JFrame)
{
Point p = ((JFrame)previous).getMousePosition();
System.out.println(p); // or do what you need to with p
}
.
要计算鼠标的位置相对于帧,必须从位置中减去鼠标的绝对位置 ,从而从框架的左上角取消外来点到屏幕的左上角。
将鼠标的位置相对于帧作为 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);
}
.
将x作为 int :
public int getXRelativeTo() {
int x = frame.getX() - MouseInfo.getPointerInfo().getLocation().x;
return x;
}
.
将y作为 int :
public int getXRelativeTo() {
int y = frame.getY() - MouseInfo.getPointerInfo().getLocation().y;
return y;
}
.
我希望得到帮助。:)
获取更多信息,访问 http://文档.oracle.com / javase / 7 / docs / api / java / awt / mousinfo.html
不隶属于 StackOverflow