JTextField 的观察者模式?
假设我有一个类:
class Boy
{
int age = 25;
}
我有一个 JTextField,age,它更新 Boy 的“age”实例字段。或者,如果男孩的年龄以另一种方式更改(可能是 setAge() ),我需要能够在 JTextField 中反映此更改。
使用观察者模式是一种方法。在这种情况下,我是否被迫创建一个新类 JTextFieldThatObserves (它继承自 JTextField 并实现 Observer)
默认的 JTextField 无法执行我需要它执行的操作?
Suppose I have a class:
class Boy
{
int age = 25;
}
I have a JTextField, age, that updates the 'age' instance field of Boy. Alternatively, if the age of the boy is changed another way (perhaps, setAge() ), I need to be able to reflect this change in the JTextField.
Using the observer pattern is one way. In this case, am I forced to create a new class JTextFieldThatObserves (which inherits from JTextField and implements Observer)
Is the default JTextField incapable of doing what I need it to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java 没有附带用于 Swing 组件和对象字段的自动绑定框架。这是它的一大缺陷!
恐怕做到这一点的唯一机制是在小部件和对象上使用观察者模式,并注意无限循环。
在这些情况下,PropertyEditor 很有用,因为它可以让您免于创建无数不同的侦听器/事件类。
Java does not ship with an automatic binding framework for Swing components and an object's fields. This is one of its major flaws!
I'm afraid the only mechanism to do this is to use the observer pattern on both the widget and the object and watchful of infinite cycles.
One thing useful in these cases is a
PropertyEditor
as it saves you from creating a gazillion different listener/event classes.如果您要做的不仅仅是少量的此类事情,我强烈建议您花一点时间学习可用于 Java 的绑定框架之一。我个人使用 Better Beans Bindings。
If you are going to be doing more than a trivial amount of this sort of thing, I strongly suggest that you invest a little time learning one of the binding frameworks available for Java. I personally use Better Beans Bindings.