Is this the right way of doing this? Iam using the MVC pattern.
in my View class, i have aButton.
Button fooButton = new Button();
public void addFooButtonListener(ActionListener foo){
fooButton.addActionListener(foo);
}
In my Controller class constructor:
this.theView.addFooButtonListener(new Listener());
In the Controller Class I use a inner Class named Listener
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e){
//do whatever i want
}
}
I have been told, that this is not the right way of doing this? is this true? If yes, what is the right way?
As shared, your current code is perfectly fine and there is no issue in it. However, you could have used below implementations :
Anonymous Class:
new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// To Do :: Task here
}
}
Lambda Expressions:
button.addActionListener(e -> {
// Task implementation here
});
Though it depends upon requirement, but the only disadvantage I can see in your implementation is the case when you have multiple button with different actions, which will end up in large amount of inner classes.
Also, if you feel that the same action can be used in different class, you can also make a separate class implementing ActionListener in maybe listeners package and then use it among all classes.
Again, that all is requirement specific and accordingly you can choose whatever suits you the best in your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With