2013-10-07 44 views
3

我正在用java開發一個重擊遊戲。我正在創建一個10 * 10的按鈕網格。不過,我無法訪問actionlistener中單擊按鈕的ID。這是我迄今爲止的代碼。如何在java swing中爲按鈕的網格實現actionlistener?

String buttonID; 
    buttonPanel.setLayout(new GridLayout(10,10)); 
    for (int i = 0; i < 10; i++) { 
     for (int j = 0; j < 10; j++) { 
      buttonID = Integer.toString(++buttonCount); 
      buttons[i][j] = new JButton(); 
      buttons[i][j].setName(buttonID); 
      buttons[i][j].addActionListener(this); 
      buttons[i][j].setDisabledIcon(null); 
      buttonPanel.add(buttons[i][j]); 
     } 
    } 

    public void actionPerformed(ActionEvent ae) { 
    if (ae.getSource()==startButton) { 
     System.out.println("Game has been started"); 
    } 
    if (ae.getSource() == "34") { //please see the description below 
     System.out.println("Yes I have clicked this button"); 
    } 
    else { 
     System.out.println("Other button is clicked"); 
    } 
} 

目前我剛剛印刷的幾件事情。我不知道如何比較ae.getsource()和被點擊的按鈕。我試圖用「34」來比較它。但是當我點擊網格上的第34個按鈕時,它仍然會打印「其他按鈕被點擊」。

回答

3

使用按鈕actionCommand屬性來唯一地標識每個按鈕按您的要求......

for (int i = 0; i < 10; i++) { 
    for (int j = 0; j < 10; j++) { 
     buttonID = Integer.toString(++buttonCount); 
     //... 
     buttons[i][j].setActionCommand(String.toString(buttonID)); 
     //... 
    } 
} 

然後actionPerformed方法,簡單的外觀了ActionEventactionCommand財產....

public void actionPerformed(ActionEvent ae) { 
    String cmd = ae.getActionCommand(); 
    if ("0".equals(cmd)) { 
     //... 
    } else if ... 

同樣,你可以用你的buttons基於陣列的ActionEvent的源

上找到按鈕
public void actionPerformed(ActionEvent ae) { 
    Object source = ae.getSource(); 
    for (int i = 0; i < 10; i++) { 
     for (int j = 0; j < 10; j++) { 
      if (source == (buttons[i][j])) { 
       //... 
       break; 
      } 
     } 
    } 

但是,這取決於你...

+0

非常感謝!這就是我想知道的:) – newbie

+0

@YashKelkar請接受答案,如果它解決了你的問題。謝謝。 – Sorter

+0

我可能會在那個地方使用'source ==按鈕[i] [j]',因爲你不需要值相等,但是在那裏引用相等。 – Joey

1

使用按鈕對象,而不是字符串。您不需要跟蹤按鈕的ID或名稱。只需循環所有按鈕即可找出源。

創建按鈕時,您可以將列表中的所有按鈕都按下。在找到源代碼時,遍歷它們。

使用setActionCommand() & getActionCommand()而不是setName()處理按鈕疲憊不堪

for(JButton button : buttonList) 
    if (ae.getSource() == button) { 
     //Do required tasks. 
    } 
+0

非常感謝! – newbie