Java Swing: Button's specific id. How can I catch pressed button in listener not using .getActionCommand?

StackOverflow https://stackoverflow.com/questions/12438558

Pregunta

I have to write an ActionListener to JPanel.

The task, depending on the button pressed to cause the required action. The only way that I know - to get the label from the button using event.getActionCommand() and depending on that string to cause the desired action.

But I think that to have a binding to the label is wrong way, very wrong way. Are there other options?

In other words my question is: How can I determinate pressed button?

¿Fue útil?

Solución

Swing is an event driven architecture. So whenever you're trying to perform any type of interaction with a component, you would ideally be capturing or working with the corresponding event associated with the component.

What you would need to do is add an ActionListener, and when an action is performed (pressing of the button in this case), you would be calling the method (the "required action") you were talking about in your code. If you're new to ActionListener, you might find: "How to Write an Action Listener" to be helpful

Otros consejos

One thing I've done is something like this:

// Action Listener method
public void actionPerformed(ActionEvent e) {
    // Did somebody push my button?
    if (e.getSource() == myButton) {
        myCaller.doButton(myButton, myValue);
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top