2011-09-22 22 views
10

Tengo mis botones funcionando bien, y yo soy un oyente a cada botón de la siguiente manera:¿Cómo puedo saber en qué botón se hizo clic?

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

Aquí, como se puede ver que el oyente se llama, y ​​yo quiero averiguar qué botón I' m haciendo clic. ¿Hay una manera de hacer eso?

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

Necesito alguna forma de encontrar el botón en la matriz.

+1

fundido primero la fuente de botón, a continuación, obtener la etiqueta ((Button) actionEvent.getSource()). GetLabel() ... – Rudy

Respuesta

21

probar esto

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

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

wow muchas gracias java seguro tiene muchas cosas, pero algunas funciones son impresionantes – Makenshi

+0

Pruebe [this] (http://download.oracle.com/javase/7/docs/api/java/awt/event/ActionEvent.html #method_summary) (luego sigue los enlaces a las clases de las cuales 'ActionEvent' hereda y también verifica los métodos de esos). Los JavaDocs: muy útiles para este tipo de cosas. ;) –

5

ActionEvent tiene un método getActionCommand() que obtendrá una ActionCommand String de JButton. Esto también suele ser texto (para JButtons).

+0

1 por mencionar 'getActionCommand()' pero sobre todo para * "Esto es ** generalmente ** es texto también" * (énfasis mío). –

5

el fin de obtener la etiqueta, intente esto.

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

No sé de quién es la pregunta que estás respondiendo, pero no parece ser la pregunta hecha por Makenshi. –

Cuestiones relacionadas