java 查找相对于面板的鼠标位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12866205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding Mouse Position relative to a panel
提问by DMCH
I'm trying to get the mouse's position within a panel, as in the top left of the panel = x/y 0,0.
我试图在面板中获取鼠标的位置,如面板左上角 = x/y 0,0。
What I have at the minute gives the position on the entire screen, so depending on where the panel (which is in a frame) is on the screen, the coordinates are different. I guess you could add to the x/y co-ordinates to account for this, but this seems like a messy solution. Can anyone help?
我现在所拥有的给出了整个屏幕上的位置,因此根据面板(在框架中)在屏幕上的位置,坐标是不同的。我想你可以添加 x/y 坐标来解决这个问题,但这似乎是一个混乱的解决方案。任何人都可以帮忙吗?
Here's the mouseListener I'm using, which has been added to the panel.
这是我正在使用的 mouseListener,它已添加到面板中。
private class MouseListener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
// Finds the location of the mouse
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
// Gets the x -> and y co-ordinates
int x = (int) b.getX();
int y = (int) b.getY();
System.out.println("Mouse x: " + x);
System.out.println("Mouse y: " + y);
// Determines which tile the click occured on
int xTile = x/tileSize;
int yTile = y/tileSize;
System.out.println("X Tile: " + xTile);
System.out.println("Y Tile: " + yTile);
}
}
回答by Andrew Thompson
Returns the x,y position of the event relative to the source component.
返回事件相对于源组件的 x,y 位置。
回答by Reimeus
You can use MouseEvent.getX()
and MouseEvent.getY()
to get the relative co-ordinates of X & Y respectively.
您可以使用MouseEvent.getX()
和MouseEvent.getY()
分别获取 X 和 Y 的相对坐标。
int relativeX = e.getX();
int relativeY = e.getY();
...