[英]Java Swing and the Observer Pattern
I'm looking for a way to cleanly organize my UI code in Swing. 我正在寻找一种在Swing中干净组织UI代码的方法。
Let's say my UI-code is structured in the following way: 假设我的UI代码采用以下方式构建:
class MainWindow extends JFrame {
// SomePanel panel is added here
}
class SomePanel extends JPanel {
// buttons, checkboxes and so on are added here
}
Lets say I'm instantiating a MainWindow-object inside my main method: 假设我要在main方法中实例化MainWindow对象:
MainWindow frame = new MainWindow("I am an App");
What is the best practice for listening to ActionEvents of buttons (which are declared inside SomePanel, which is declared inside MainWindow) from within my main-method? 从我的主方法中侦听按钮的ActionEvent(在SomePanel内部声明,在MainWindow内部声明)的最佳实践是什么?
Thank you very much for your help! 非常感谢您的帮助!
Use a PropertyChangeEvent
, seen here and here , to communicate results from one container to another. 使用PropertyChangeEvent
(在此处和此处看到)将结果从一个容器传递到另一个容器。 Other ways to implement the observer pattern are mentioned here . 这里提到了实现观察者模式的其他方法。
Addendum: You're suggesting writing custom ActionEvents
? 附录: 您建议编写自定义ActionEvents
?
EventListenerList
is another way to implement the observer pattern. EventListenerList
是实现观察者模式的另一种方法。 Such a list is common to every JComponent
, and it is appropriate when more than one event type must be managed. 这样的列表对于每个JComponent
都是通用的,并且当必须管理多个事件类型时,它是合适的。 JFreeChart
is another popular example that uses diverse events to update chart subcomponents when the data model is changed. JFreeChart
是另一个流行的示例,它在更改数据模型时使用各种事件来更新图表子组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.