Reputation: 193
So I was wondering what is the better looking solution/what are the differences and what are things to think about when making the decision about making either several listeners (1 listener for 1 button) or just 1 ActionListener
for all buttons in my GUI (about 10 Buttons) and getting the information about which button was pressed through actionevent.getSource() == buttonname
.
What is the better style in your opinion? Is there a disadvantage on creating so many classes for several ActionListeners
? Or will it not matter at all?
By the way, in my code im trying to stick to the model-view-controller organization.
Upvotes: 0
Views: 784
Reputation: 289
I prefer to use lambdas, one per each button, e.g.:
JButton button = new JButton("Button");
button.addActionListener(e -> //do your work here);
Upvotes: 0
Reputation: 1737
JButton button = new JButton("Button");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//do your work here.
}
});
This is the way to go for each button.
A long ActionListener
interface object with multiple if else or switch statements is both clumsy and hard to maintain.
Additionally, on each button press, the program has to go through a number of matchings to get to know what button was pressed. That is very expensive.
So, one Button
---> one ActionListener
is the better way.
Upvotes: 1
Reputation: 319
I prefer to have different ActionListener classes but grouping them by functional responsibility is a good practice in my experience.
I also suggest you relying on ActionEvent#getActionCommand()
over ActionEvent#getSource()
because you could handle an equivalent action from different UI components.
Upvotes: 2