2012-05-08 30 views
0

下面是我的代碼的ActionListener部分。專注於重置按鈕。Java - 我無法讓兩個actionListener正常工作

public void actionPerformed(ActionEvent e) { 
    int i; 
    for (i = 0; i < 26; i++) { 
     if (e.getSource() == a[i]) { 
      consultWord(i); 
     } 
    } 

    if (e.getSource() == reset) { 
     Hangman gui = new Hangman(); 
     System.out.print("test"); 
     gui.go(); 
    } 
} 

顯然有它上面得多(因爲這是在最後)。按鈕數組1(頂部if語句)完美地工作。按鈕2(底部if語句)完全不起作用。測試輸出文本不會出現。這是我宣佈變量的地方。 (它們可用於所有代碼)。

JButton reset = new JButton("Reset"); 
private Button a[]; 

如果它意味着你什麼都好,這裏是爲建立一個[]按鈕的代碼。

int i; 
StringBuffer buffer; 
a = new Button[26]; 
topPanel.setLayout(new GridLayout(4,0, 10, 10)); 
for (i = 0; i <26; i++) { 
    buffer = new StringBuffer(); 
    buffer.append((char)(i+'a')); 
    a[i] = new Button(buffer.toString()); 
    a[i].setSize(100,100); 
    a[i].addActionListener(this); 
    topPanel.add(a[i]); 
} 

任何想法爲什麼我的底部按鈕沒有做蹲?如果需要,我會粘貼我的整個代碼。

回答

0

也許你只是忘了添加ActionListener到你的reset按鈕?這是從上面的代碼中丟失......


作爲一個側面說明了一些建議,使你的代碼更加清晰:

  • ,則不需要StringBuffer:只需使用String.valueOf((char)(i+'a'))
  • 我不會用同樣的ActionListener你所有的按鈕,因爲這混亂了你的actionPerformed方法。 Anonymous inner classes在這裏很有用。