Finding Mouse Position relative to a panel

泪湿孤枕 提交于 2019-12-08 17:43:35

问题


I'm trying to get the mouse's position within a panel, as in the top left of the panel = 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?

Here's the mouseListener I'm using, which has been added to the panel.

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);

    }
}

回答1:


See MouseEvent.getPoint().

Returns the x,y position of the event relative to the source component.




回答2:


You can use MouseEvent.getX() and MouseEvent.getY() to get the relative co-ordinates of X & Y respectively.

int relativeX = e.getX();
int relativeY = e.getY();
...


来源:https://stackoverflow.com/questions/12866205/finding-mouse-position-relative-to-a-panel

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