• Post Reply Bookmark Topic Watch Topic
  • New Topic

Implementing EventHandlers  RSS feed

 
Sudharsan Govindarajan
Ranch Hand
Posts: 319
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For event handling in Swing, there are two approaches now.
One is having an inner class for each of the component and the
other is to have the main class implement the Listener Interface and adding it to the components..
What are the advantages/disadvantages in these two methods? Which one is the best?
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using inner classes or implementing the listener in the main class give pretty much the same benefits. You can access private data in the class directly in the listener. If you implement the listener in the class and have multiple components you are listening to, you'll need to have conditional statements to figure out which component triggered the listener so you'll know what to do in the listener. If you use inner classes you'll just use multiple inner classes.

If you just need a special listener for one component, I would use an anonymous inner class to define the listener. If you have several components that may want to use the functionality in the same class, use a regular inner class. I usually use a regular inner class, because it is easier to refactor into a generic stand-alone listener class if I need to use the same listener in another class.
 
Sudharsan Govindarajan
Ranch Hand
Posts: 319
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Nathan! But i want to know whether there are any performance differences between the two approaches. Like the time needed to load the number of inner classes, like that...
 
balazs erdohelyi
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following link might help you:
http://www.javaworld.com/javaworld/javaqa/2002-03/02-qa-0322-morelisteners.html?
bye,
Balazs
 
Sudharsan Govindarajan
Ranch Hand
Posts: 319
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah balazs! Thanks for that link. I'm more clearer now.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!