2012-03-22 73 views
1

我是Java新手。Java多個按鈕座標

我正在開採礦山。我用paramteres(x_length,y_length)使用GridLayout。我想知道我按下了哪個按鈕 - >他的座標(x,y)。但是,如果我將它輸入到監聽器,它會給我錯誤 - >將修飾符'x'更改爲final。 所以我的問題是我怎麼才能簡單地得到按鈕的座標?

而且我也想問一下,我怎樣才能簡單地改變按鈕的大小? setSize不適用於我。

for (int y = 0; y < y_length; y++) 
    { 
     for (int x = 0; x < x_length; x++) 
     {    
      buttons[x][y] = new JButton("X"); 

      buttons[x][y].addMouseListener(new MouseAdapter() 
      { 
       public void mouseClicked(MouseEvent e) 
       { 
        if (e.getButton() == MouseEvent.BUTTON1) 
        { 
         //exception -> Cannot refer to a non-final variable x inside an inner class defined in a different method 
         JOptionPane.showMessageDialog(null, "Left -> " + x + " | " + y); 
        } 
        else if (e.getButton() == MouseEvent.BUTTON3) 
        { 
         JOptionPane.showMessageDialog(null, "Right -> " + x + " | " + y); 
        } 
       } 
      }); 
      mines_array.add(buttons[x][y]); 
     } 
    } 
+0

1)爲了更好地幫助越早,張貼[SSCCE(http://sscce.org/)。 2)最好每個問題提出一個問題。 3)佈局管理器通常會在整個大小上遵守組件的首選大小。 4)請複製/粘貼錯誤信息和異常輸出,並使用代碼格式化。 5)'ActionListener'可能更適合這個GUI中的按鈕。它有什麼作用? – 2012-03-22 09:19:27

+0

你不能在循環中不斷改變x和y'final'。你可以做什麼(但它是一個醜陋的黑客,這就是爲什麼我不把它作爲答案),在嵌套循環中放置一個聲明:'final int x2 = x; final int y2 = y',並在您的偵聽器中引用'x2'和'y2'。如Andrew所說,「ActionListener」更合適,並且設置preferredSize而不是大小。 – 2012-03-22 09:22:47

回答

2

,必須先創建一個自定義類監聽器,而不是一個匿名的一個,因爲它需要的參數(x和y)。

private static class ButtonMouseListener extends MouseAdapter { 
    private final int x; 
    private final int y; 

    public ButtonMouseListener(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 

    public void mouseClicked(MouseEvent e) { 
     if (e.getButton() == MouseEvent.BUTTON1) { 
      JOptionPane.showMessageDialog(null, "Left -> " + x + " | " + y); 
     } else if (e.getButton() == MouseEvent.BUTTON3) { 
      JOptionPane.showMessageDialog(null, "Right -> " + x + " | " + y); 
     } 
    } 
} 

然後,你可以用你這樣的代碼:

for (int y = 0; y < y_length; y++) { 
    for (int x = 0; x < x_length; x++) {    
     buttons[x][y] = new JButton("X"); 
     buttons[x][y].addMouseListener(new ButtonMouseListener(x, y)); 
     mines_array.add(buttons[x][y]); 
    } 
} 

這一切,有樂趣。 關於按鈕的大小,如果您在其父容器中使用佈局,則它們的大小將由佈局自動計算,並且不能使用setSize()更改。