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

DMC*_*MCH 7 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);

    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*son 7

请参阅MouseEvent.getPoint().

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