为什么 extends JFrame implements ActionListener
是一个糟糕的设计决策?
最佳答案
几点:
- 扩展
JFrame
可能是一种错误的方法 - 在
JFrame
上实现ActionListener
可能会生成非 OOP 代码。
错误的方法?
如果这个想法是制作一个 GUI 应用程序,那么,不是在制作 JFrame
的扩展,而是实际编写一个应用程序。
因此,JFrame
将成为应用程序的一部分,而不是应用程序本身。因此,JFrame
应该是类中的一个对象。
在 JFrame
上实现 ActionListener
可能会导致非 OOP 代码
考虑以下情况——当 GUI 应用程序开始变大时,我们开始添加大量按钮和菜单,从而产生 ActionEvent
。
如果 JFrame
本身要获取事件,那么 actionPerformed
方法会是什么样子?
大概是这样的:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
// Find out which component fired the event
if (source == masterButton) {
// ... do something
} else if (source == anotherButton) {
// ... do something else
} else if (...)
// ... and so on ...
} else if (...)
// ... and so on ...
}
}
哎呀。
我们将开始获取与应用程序中所有组件紧密耦合的代码,并且可维护性很快就会消失。
例如,如果 GUI 应用程序具有响应每个组件的 ActionLister
实例,那么我们将能够分解操作和 actionPerformed< 的耦合
GUI 中所有组件的方法。
例如:
JButton masterButton = new JButton();
masterButton.addActionListener(new MasterButtonActionListener());
JButton anotherButton = new JButton();
anotherButton.addActionListener(new AnotherButtonActionListener());
这样,每个按钮都会有 ActionListeners
,它们可能具有不同的功能。 MasterButtonActionListener
的职责是处理来自 masterButton
的事件——它不必知道应用程序中的其他按钮。
此外,这将促进组件在其他应用程序或应用程序其他部分中的可重用性,而无需复制并粘贴 actionPerformed 中的整体
方法。if-else
语句的部分
关于java - JFrame子类和ActionListener接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4606815/