查找相对于面板的鼠标位置

时间:2012-10-12 19:57:45

标签: java swing mouselistener mouse-position

我正试图让鼠标在面板中的位置,如面板的左上角= x / y 0,0。

我现在所拥有的位置在整个屏幕上给出了位置,因此根据面板(在一个框架中)在屏幕上的位置,坐标是不同的。我想你可以添加到x / y坐标来解释这一点,但这似乎是一个混乱的解决方案。有人可以帮忙吗?

这是我正在使用的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);

    }
}

2 个答案:

答案 0 :(得分:7)

请参阅MouseEvent.getPoint()

  

返回事件相对于源组件的x,y位置。

答案 1 :(得分:3)

您可以使用MouseEvent.getX()MouseEvent.getY()来获取X和的相对坐标; Y分别。

int relativeX = e.getX();
int relativeY = e.getY();
...
相关问题