是的,这在很大程度上取决于您要做什么。我认为匿名内部类由于两个神话而受到了不好的批评。一是不能重用匿名代码。第二,内存泄漏。但是这些都可以通过简单的方法轻松解决。保存对实例的引用。对于共享代码,只需创建对匿名内部类的引用。
Action action = new AbstractAction("Open") {...};
JButton button = new JButton( action );
JMenuItem menuItem = new JMenuItem( action );
panel.getActionMap().put("openFile", action );
现在,您可以跨多个组件重用该操作。对于后面的内存泄漏问题,您可以使用该引用来取消注册它,或者第二个更简单的选项是 WeakListeners。WeakListeners 的优点是在创建后不需要对其进行管理。
至于风格,我发现匿名侦听器非常方便,并且在某些情况下在处理 Swing 中的线程时更易于阅读,因为它将您的代码保持在一种方法中(invokeLater、executeInBackground 等)。当您匿名侦听器委托给一个实例方法时,我认为它将您无法读取侦听器之前发生的事情的代码与一个屏幕中与侦听器关联的逻辑分开。他们往往会分开,而且更难追随。
Something to be aware of is if you use ActionMaps most of the memory leaks will go away associated with keyboard listening. Unfortunately things like focus listeners or listeners that are registered with central systems are still a problem. (Again WeakListeners are great here). And you already have a place to keep the action with every component so no need to create extra instance variables to hold it. If you need to reuse across two components (say in a menu bar and in a control) create a separate class.