2012-10-12 24 views
7

パネルの左上のように、パネル内でマウスの位置を取得しようとしています。パネルの相対的なマウス位置を見つける

私が分かっていることは、画面全体の位置を示します。そのため、パネル(フレーム内にある)が画面上のどこにあるかによって、座標が異なります。私はこれを説明するためにx/y座標に加えることができると思いますが、これは面倒な解決策のようです。誰も助けることができますか?

私は使用しているマウスリスナーをパネルに追加しました。

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

    } 
} 

答えて

7

MouseEvent.getPoint()を参照してください。

ソースコンポーネントに対してイベントのx、y位置を返します。

+1

あなたは紳士で学者です! – DMCH

3

あなたは、それぞれX & Yの相対座標を取得するためにMouseEvent.getX()MouseEvent.getY()を使用することができます。

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

また動作します。ありがとうございました! – DMCH

関連する問題