2015-07-20 38 views
1

的位置,我有一個包含81個鍵的框架,可以說所有的按鈕不包含名稱,面積都相等,都自動設定。所以當我點擊一個我想知道哪一個被點擊。如果我使用實現MouseListener的類並使用此方法檢查每個按鈕

mouseClicked(MouseEvent e){ 
temp[0]= e.getX(); 
temp[1]= e.getY(); 
} 

如何檢查這些座標? 我是否必須爲每個按鈕設置自己的位置?

回答

0

我相信這是你在找什麼。

public static final int BUTTONS_WIDTH_COUNT = 9; 
    public static final int BUTTONS_HEIGHT_COUNT = 9; 
    public static final Button[][] BUTTONS = new Button[BUTTONS_WIDTH_COUNT][BUTTONS_HEIGHT_COUNT] 
    ... 

    // I'll assume that the buttons are taking up the entire frame so no offsets are taken into account 
    frame.addMouseListener(
     new MouseAdaptor() { 
      mouseClicked(MouseEvent e) { 
      // The X Y coordinates are relative to the component so 
      int frameWidth = frame.getBounds().getWidth(); 
      int frameHeight = frame.getBounds().getHeight(); 

      Button buttonClicked = buttons[e.getX()/(frameWidth/BUTTONS_WIDTH_COUNT)][e.getY()/(frameHeight/BUTTONS_HEIGHT_COUNT)]; 
     } 
    } 

編輯:實際上這將是好了很多相同的MouseAdaptor分配給所有的按鈕和使用e.getSource()知道哪個按鈕被聽者調用。

+0

令人驚歎的答案,謝謝。我會給你一個+1,但我不能,因爲我沒有足夠的代表:( – itsnotme

+0

沒問題,我認爲你可以暫時'批准'作爲原始海報的答案。 – Genkus