Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action vs ActionListener for multiple buttons with the same java

I would like to clarify my understanding of using Action instead of ActionListener.

If I have multiple JButtons that all require the same function to occur if they are clicked (for example the button will be disabled), would using Action be more appropriate for this?

If so, is it because you can change the state of the button (for example making it disabled) by setting the state of the Action to disabled?

Is this not possible with an actionListener?

Below is some code demonstrating the example given above:

JButton[] button = new JButton[10];

for(int i = 0; i < 10; i++){
    button[i] = new JButton();
    Action buttonAction = new ButtonAction();
    button[i].setAction(buttonAction);  
}

class ButtonAction extends AbstractAction{
    public void actionPerformed(ActionEvent e){
        setEnabled(false);
    }
}

Sorry if I have got the wrong end of the stick!

Thank you!

like image 586
user1788673 Avatar asked Jul 28 '26 02:07

user1788673


1 Answers

According to the Javadoc:

The Action interface provides a useful extension to the ActionListener interface in cases where the same functionality may be accessed by several controls.

So I'd agree with your assertion that this is the case.

like image 71
hd1 Avatar answered Jul 30 '26 20:07

hd1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!