2010-09-17 84 views

回答

0

註冊MouseListener並執行相應的事件。 MouseEvent具有可以給你鼠標位置的getX和getY方法。

+0

是的,但是當我在按鈕是JFrame中不會觸發該事件 – xdevel2000 2010-09-17 10:24:18

+0

嘗試該按鈕的事件監聽器在這個代碼: PointerInfo A = MouseInfo.getPointerInfo(); Point b = a.getLocation(); INT X =(int)的b.getX(); int y =(int)b.getY(); – 2010-09-17 10:36:00

+0

不,它給我相對於按鈕不幀的COORDS! – xdevel2000 2010-09-17 10:44:26

1

getBounds()爲您提供了相對於其父按鈕的位置和尺寸的Rectangle。在我的例子中,父母是JFrame

public class Click { 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       final JFrame f = new JFrame("Click pos"); 
       f.setSize(640, 480); 

       final JButton b = new JButton("Click Me!"); 
       b.addMouseListener(new MouseAdapter() { 
        public void mouseClicked(MouseEvent e) { 
         final JButton bb = (JButton) e.getSource(); 
         final Rectangle bbox = bb.getBounds(); 
         final int x = bbox.x + e.getX(); 
         final int y = bbox.y + e.getY(); 
         JOptionPane.showMessageDialog(f, "pos: " + x + " " + y); 
        } 
       }); 
       f.getContentPane().add(b, BorderLayout.SOUTH); 
       f.setVisible(true); 
      } 
     }); 
    } 
} 

編輯:
隨着輔助方法從SwingUtilities類的mouseClicked方法獲取簡單得多。你會得到正確的座標獨立的多少容器是JFrameJButton之間。我沒有意識到他們。

    final JButton bb = (JButton) e.getSource(); 
        Point p = SwingUtilities.convertPoint(bb, e.getPoint(), f); 
        JOptionPane.showMessageDialog(f, p);