This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes ActionListener advice Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "ActionListener advice" Watch "ActionListener advice" New topic

ActionListener advice

Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

I have a form (actually a JPanel) that will in some cases get called to stand alone and other times be part of a larger form. It has two buttons that I want to behave differently when it is part of a larger form. My instinct is to loop through the array of actionListeners for each of these buttons and remove them, then add different ones.

My question is: Would this be the proper way of doing this? If not, what is a better way?

Greg Fidster

Joined: Dec 08, 2004
Posts: 10
Maybe would be smoother to have the JFrame/JDialog thats inserting the JPanel as part of its application be responsible for placing the actions onto the buttons. Instead of having the JPanel including any logic for the actions, include public setters for each of them, and thus remaining a pleasantly dumb gui. The actions themselves can be placed in separate classes and extend the AbstractAction class. The form or larger form can then choose the appropriate action classes and attach them to the buttons via the setters.
Swati Udas
Ranch Hand

Joined: Aug 18, 2004
Posts: 121
U can add a addActionListener function to your JPanel
public addActionListener(Listener l){
U can call this function from the outer JFrame and add appropriate listener.
And u can add a default listener in the constructor of JPanel..fro standalone functionality!!

SCJP 1.4 (90%)<br />SCWCD 1.4 (88%)
Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

I like it. I can control listeners from outside the panel and set them more appropriately. That saves me from the messy business of removing them and adding others. Thank you.
Swati Udas
Ranch Hand

Joined: Aug 18, 2004
Posts: 121
Wow! It worked!!
Great..thanks a lot for the reply
I agree. Here's the link:
subject: ActionListener advice
Similar Threads
hidden parameter quesion in JS
Actions in Struts
Which layout to use?
Printing part of JSP page