aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Which is the best way to write action listeners? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Which is the best way to write action listeners?" Watch "Which is the best way to write action listeners?" New topic
Author

Which is the best way to write action listeners?

Minh Nam
Ranch Hand

Joined: Sep 10, 2011
Posts: 57
As far as I know, there are two ways to handle events, for example:

- using anonymous class action listener, all logic written in method actionPerformed() or by separate methods.
- writing concrete action listener classes (public or inner classes)

So which is the best practice, pros and cons of each, or is there something else?

Please discuss.
Thanks.


Advanced java topics
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4490
    
    8

Well, one case where you definitely need to use the concrete class is if you need to have more than one instance of the listener. For instance, if you need two event handlers that work in exactly the same way except that some parameters are different - I'd usually use a named inner class with a constructor that lets me set the parameters and then create as many of them as a necessary.

For simple event handlers, I prefer anonymous inner classes.

(There's a third way, of making the containing class implement the listener interface, but that's usually a poor design).
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
That was the short answer, from Matthew B. Here is the long answer, and thisis an old discussion about problems with Listeners. The older link at the beginning of the second thread I quoted might be worth reading too.

You will notice MB and I agree completely on this point.
Minh Nam
Ranch Hand

Joined: Sep 10, 2011
Posts: 57
Thanks both guys
I am reading the old posts...
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3611
    
  60

Sometimes Swing's AbstractAction can be put to a really good use, especially if the same action should be accessible from multiple UI controls (eg. a menu item and a toolbar button). It is definitely worth checking out. The greatest thing about it is that you can enable/disable the action itself and all associated controls get updated automatically. Neat.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Good idea about Actions. An AbstractAction is an ActionListener, and I tried one for practice here.
Minh Nam
Ranch Hand

Joined: Sep 10, 2011
Posts: 57
I have checked the AbstractAction class and the JMenu and JToolbar, they have a useful method: add(Action) which cuts down the written code significantly.
Thanks guys
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
You're welcome
 
Consider Paul's rocket mass heater.
 
subject: Which is the best way to write action listeners?