我正在寻找一种在 Swing 中干净地组织我的 UI 代码的方法。
假设我的 UI 代码结构如下:
class MainWindow extends JFrame {
// SomePanel panel is added here
}
class SomePanel extends JPanel {
// buttons, checkboxes and so on are added here
}
假设我在我的 main 方法中实例化一个 MainWindow 对象:
MainWindow frame = new MainWindow("I am an App");
从我的主方法中监听按钮的 ActionEvents(在 SomePanel 中声明,在 MainWindow 中声明)的最佳实践是什么?
非常感谢您的帮助!
最佳答案
使用 PropertyChangeEvent
,参见 here和 here , 将结果从一个容器传送到另一个容器。其他实现 observer pattern 的方法提到here .
附录:您建议编写自定义 ActionEvents
?
EventListenerList
是实现观察者模式的另一种方式。这样的列表对于每个 JComponent
都是通用的,当必须管理多个事件 type 时,它是合适的。 JFreeChart
是另一个流行的示例,它在数据模型更改时使用不同的事件来更新图表子组件。
关于Java Swing 和观察者模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14343452/