button1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
exite.setEnabled(true);
}
});
button2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
exite.setEnabled(true);
}
});
button3.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
exite.setEnabled(true);
}
});
I have 3 buttons here, but they are doing same thing. It takes some space in code. How can I group them all and assigned to one ActionListener?
Something like this. I don't know how it should be.
button1.button2.button3.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
exite.setEnabled(true);
}
});
Just assign the ActionListener
to a different variable first:
ActionListener listener = new ActionListener() {
...
};
button1.addActionListener(listener);
button2.addActionListener(listener);
button3.addActionListener(listener);
It's just a reference after all - the only "special" thing here is the use of an anonymous inner class to create an instance of ActionListener
.
If there are multiple things that you want to do with all your buttons, you may well want to put them into a collection rather than having three separate variables for them, too.
See more on this question at Stackoverflow