• Post Reply Bookmark Topic Watch Topic
  • New Topic

Swing ActionListeners best practice?  RSS feed

 
Tad Dicks
Ranch Hand
Posts: 264
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whats the best practice for implementing action listeners?

I've seen it done basically 2 different ways in Java books.
1. Have the class where the components are located implement Actionlistener
and then having the line:
someComponent.addActionListener(this);
or
2. creating an anonymous inner class like:

and then having the line:
someComponent.addActionListener(act);

Is there a perforance difference?
Does it matter?

-Tad
 
Joe Ess
Bartender
Posts: 9429
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tad Dicks:

Is there a perforance difference?


If there is, it is dwarfed by practically everything else the application is doing (i.e. file IO, database access, socket connections, painting and so on). (NOTE: stupid code is exempt from the previous comment)


Does it matter?


I think it matters more from a code maintenance standpoint more than anything else. Make your code consistent and clean and I don't think anyone can complain.
BTW, there's at least one more way: Action
 
Mahesh x Bogadi
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I feel the 2nd method is good and clear.
 
Mahesh x Bogadi
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the 2nd method is good and clear.
 
Tad Dicks
Ranch Hand
Posts: 264
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe, thanks for the link. I've seen that interface used before(though not very often). I think I like it better as it seems a bit more flexible however I saw this on the link:

Note that Action implementations tend to be more expensive in terms of storage than a typical ActionListener, which does not offer the benefits of centralized control of functionality and broadcast of property changes. For this reason, you should take care to only use Actions where their benefits are desired, and use simple ActionListeners elsewhere.
 
Pat Hays
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The 2nd method is better and clearer.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!