mohsen.nour
mohsen.nour

Reputation: 1147

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

Upvotes: 5

Views: 4571

Answers (2)

R2B2
R2B2

Reputation: 1591

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.

Upvotes: 5

MadProgrammer
MadProgrammer

Reputation: 347184

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...

Upvotes: 4

Related Questions