2011-05-25 67 views
1

我正在做許多齧合類的井字遊戲,我遇到了一個小問題。在我的版本中,我正在嘗試使板尺寸變量,這意味着代表每個方塊的按鈕不能輕鬆引用。有沒有辦法確定哪個按鈕被點擊,如果是這樣,怎麼辦?謝謝!訪問GridLayout中的按鈕

public class GameView extends JFrame{ 
    private static final long serialVersionUID = -2869672245901003704L; 
    public TicBoard game; 
    private GridLayout view; 

    public GameView(int height, int width)//height and width are coordinates (-y,x) across all classes 
    { 
     super("Tic Tac Toe"); 
     game = new TicBoard(height, width); 
     view = new GridLayout(height,width); 

     this.setLayout(view); 
     for(int h = 0; h<height; h++) 
      for(int w = 0;w<width;w++) 
       this.add(game.getButton(h,w)); 

    }  
} 
+0

「在我的版本中,我正在嘗試使主板大小變化,」JButton []'(或'JButton [] []')可以根據需要製作任意大小。該數組可以保持對按鈕的引用。 – 2011-05-25 04:25:36

回答

4

有沒有一種方法,以確定哪些 按鈕被點擊,如果是這樣,如何?

是的。

ActionListener添加到按鈕,然後在actionPerformed(ActionEvent e){...}方法您將有e.getSource()方法來確定哪個已觸發此方法意味着哪個按鈕被按下。