Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Mouse Position relative to a panel

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

    }
}
like image 784
DMCH Avatar asked Oct 12 '12 19:10

DMCH


People also ask

How do I find the cursor position in an element?

You can use the jQuery event. pageX and event. pageY in combination with the jQuery offset() method to get the position of mouse pointer relative to an element.

What is the correct statement that gets the position of mouse position?

To determine the mouse's current position, we use the statement, pyautogui. position(). This function returns a tuple of the position of the mouse's cursor. The first value is the x-coordinate of where the mouse cursor is.


1 Answers

See MouseEvent.getPoint().

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

like image 127
Andrew Thompson Avatar answered Oct 23 '22 20:10

Andrew Thompson