declare more then one ActionListener

50 Views Asked by At

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());

1

There are 1 best solutions below

2
queeg On

In both your examples your actionPerformed method seems capable of handing events from multiple sources. In that case a single instance is absolutely sufficient.

But what would you do if actionPerformed needs 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.