有一个bean(类似POJO)并且想要为它的GUI组件制作模型。因此,我需要通知GUI组件可以反映的每个属性更改。
怎么做?我应该在我的bean中放置通知和监听器存储代码吗?但这会使它“变脏”。可能会写一些包装?但这会重复吸气者和制定者。
在Commons或其他地方是否有任何库和/或辅助对象?
更新
还假设我有AbstractList<E>
实施。如何快速“归化”它,即让它通知听众变化?例如,通过触发ListDataEvent
。我知道我可以实施AbstractListModel<E>
而不是AbstractList<E>
,但看起来更糟。我希望保持“pojo-like”......
答案 0 :(得分:2)
看看FXCollections
(JDK 7):
List<String> list = new ArrayList<String>();
list.add("s1");
list.add("s2");
ObservableList<String> observableList = FXCollections.observableList(list);
observableList.addListener(new ListChangeListener<String>() {
@Override
public void onChanged(Change<? extends String> change) {
while (change.next()) {
if(change.wasAdded()){
System.out.printf("added: %s, from: %d, to: %d%n", change.getAddedSubList(), change.getFrom(), change.getTo());
}else
if(change.wasReplaced()){
System.out.printf("replaced: %s, from: %d, to: %d%n", change.getAddedSubList(), change.getFrom(), change.getTo());
}
}
}
});
observableList.add("s3");
observableList.set(1, "s1-new-value");
这将导致输出:
added: [s3], from: 2, to: 3
added: [s1-new-value], from: 1, to: 2
答案 1 :(得分:1)
你可以使用像PropertyChangeSuppport
这样的东西,也可以自己动手,例如......
public class Person {
private String name;
private final PropertyChangeSupport support;
public Person() {
this.support = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
support.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
support.removePropertyChangeListener(listener);
}
public void setName(String value) {
if (name == null ? value != null : !name.equals(value)) {
String old = name;
name = value;
support.firePropertyChange(name, old, name);
}
}
public String getName() {
return name;
}
}