I'm learning GUI programming with Java right now and I'm trying to make my first owns Application.
I use ActionListeners in them. My Question is if it is more effective to declare just one ActionListener and reference it all the time or if I should declare one for every Button, TextField, etc. I use?
//pseudo code
either:
myButton1.addActionListener(Main.getListener());
myButton2.addActionListener(Main.getListener());
or:
myButton1.addActionListener(new MyListener());
myButton2.addActionListener(new MyListener());
In both your examples your
actionPerformedmethod seems capable of handing events from multiple sources. In that case a single instance is absolutely sufficient.But what would you do if
actionPerformedneeds to do different stuff for each and every UI component? Either it would get pretty complex of doing it all, or you have many different actionlisteners that do one job only.Reusability in general is higher if you create many small listeners, so prefer that pattern whenever you can. But the criteria is not every button but every actionperformed implementation.