aspose file tools*
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
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "ActionListener advice" Watch "ActionListener advice" New topic
Author

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?

Tim
Greg Fidster
Greenhorn

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.
hth
cheers
Swati Udas
Ranch Hand

Joined: Aug 18, 2004
Posts: 121
U can add a addActionListener function to your JPanel
public addActionListener(Listener l){
button1.addActionListener(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: http://aspose.com/file-tools
 
subject: ActionListener advice