2011-09-22 103 views
10

我有我的按鈕工作的權利,我就是一個監聽器,這樣每個按鈕:如何找出哪個按鈕被點擊?

for(int i = 0; i <= 25; ++i) { 
    buttons[i] = new Button(Character.toString(letters[i])); 
    buttons[i].addActionListener(actionListener); 
    panel1.add(buttons[i]); 
} 

在這裏,你可以看到監聽器被調用,我想找出我的按鈕點擊。有沒有辦法做到這一點?

ActionListener actionListener = new ActionListener() { 
    public void actionPerformed(ActionEvent actionEvent) { 
     System.out.println(actionEvent.getSource()); 
    } 
}; 

我需要一些方法來找到數組中的按鈕。

+1

投第一源按鈕,然後獲取標籤((按鈕)actionEvent.getSource())。getLabel()... – Rudy

回答

21

試試這個

ActionListener actionListener = new ActionListener() 
{ 
     public void actionPerformed(ActionEvent actionEvent) { 

      System.out.println(actionEvent.getActionCommand()); 
     } 
    }; 
+0

哇非常感謝你肯定有很多東西,但一些功能是真棒 – Makenshi

+0

嘗試[這](http://download.oracle.com/javase/7/docs/api/java/awt/event/ActionEvent.html #method_summary)(然後按照指向ActionEvent繼承的類的鏈接,並檢查這些類的方法)。 JavaDocs - 這種東西非常方便。 ;) –

5

ActionEvent有一個方法getActionCommand(),它將得到一個JButton的actionCommand字符串。這通常也是文本(用於JButtons)。

+0

+1提'getActionCommand()',但特別是對*「這通常是**,它也是文字」*(強調我的)。 –

5

爲了獲得標籤,試試這個。

ActionListener actionListener = new ActionListener() 
{ 
     public void actionPerformed(ActionEvent actionEvent) { 
      JButton button = (JButton)actionEvent.getSource(); 
      String label = button.getLabel(); //Deprecated 

      String label2 = button.getText(); 
    } 
}; 
0
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {           
l1.setText("");//name of level what you want 

t1.setText(null);//text field what you want 

t2.setText(null);//text field what you want 
} 
+3

我不知道你回答的是誰的問題,但似乎並不是Makenshi提出的問題。 –

相關問題