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?
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.
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
posted 16 years ago
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...