Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use of multiple actionlistener for a button

I always use one ActionListenr for a button, but I find that one component can be assigned multiple action listeners. How we can do that and what is use of it Thanks in advance

like image 714
mohsen.nour Avatar asked Jan 09 '23 22:01

mohsen.nour


2 Answers

c.addActionListener(actionlistener1);
c.addActionListener(actionlistener2);

It is useful if you need to do several actions that are not necessarily correlated. For example, changing the background color of a button vs appending the action in a Logger vs informing the controller that the button have been pressed, etc...

This allows to be modular: each actionListener can handle a very specific task for a group of components. For example, you can write a default actionListener for all your buttons, and a specific one for a group of buttons that have the same behaviour.

Finally, some objects already have listeners when you instantiate them (JButton have a default FocusListener, JScrollPane a default MouseWheelListener, etc). This allow you to add other behaviours to your components, without overriding previous ones.

like image 107
R2B2 Avatar answered Jan 12 '23 12:01

R2B2


How we can do that

That's the easy part, create multiple instance of ActionListeners and use addActionListener. One would assume that they are all different...

and what is use of it

That's a harder question. One could assume that you would use multiple listeners when you want to apply newer logic to the process but not extend from the existing functionality...

Let's say you have a login form. You have a "Login" button. You write an ActionListener to gather the required details and validate them.

Later on, you decide that the button should be disabled during that process. Normally, you would add that functionality to the original code, but for what ever reason (it's not your code etc), you can't.

You could create another ActionListener whose sole purpose was to disable the button when it was pressed.

As an example...

like image 44
MadProgrammer Avatar answered Jan 12 '23 12:01

MadProgrammer