Yes, it depends a lot on what you are trying to do. I think anonymous inner classes got a bad rap because of two myths. One cannot reuse anonymous code. And two are a memory leak. But they are easily fixed by a simple approach. Save the link to the instance. To exchange code, simply create a link to an anonymous inner class.
Action action = new AbstractAction("Open") {...}; JButton button = new JButton( action ); JMenuItem menuItem = new JMenuItem( action ); panel.getActionMap().put("openFile", action );
Now you can reuse this action for several components. For a later memory leak problem, you can use this link to cancel it, or the second and simpler option is WeakListeners. WeakListeners has an advantage that does not need to be managed after they are created.
As for the style, I think that anonymous listeners will be very convenient, and in some cases easier to read when working with threads in Swing, because it saves your code in one method (invokeLater, executeInBackground, etc.). When you listen to the anon listener in the instance method, I think that it separates the code in which you cannot read what happened before the listener, and the logic associated with the listener on one screen. They tend to be separated, and harder to follow.
Something to be aware of is that if you use ActionMaps, most memory leaks will go away by contacting you listening to the keyboard. Unfortunately, issues with focus listeners or listeners that are registered with central systems are still a problem. (Again, WeakListeners are wonderful here). And you already have a place to support the action with each component, so there is no need to create additional instance variables to store it. If you need to reuse two components (for example, in the menu bar and in the control), create a separate class.
chubbsondubs
source share