Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top