簡體   English   中英

查找相對於面板的鼠標位置

[英]Finding Mouse Position relative to a panel

我試圖讓鼠標在面板中的位置,如面板的左上角= 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);

    }
}

請參閱MouseEvent.getPoint()

返回事件相對於源組件的x,y位置

您可以使用MouseEvent.getX()MouseEvent.getY()分別獲取X和Y的相對坐標。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM