我們假設我有一個實體類Foo,它包含一些字段,getters,setter和構造函數。例如:是否可以創建一個屬性來監聽javafx中自定義對象的變化?
public class Foo {
private Integer a = 0;
private Integer b = 0;
public Foo() {
}
public Integer getA() {
return a;
}
public void setA(Integer a) {
this.a = a;
}
public Integer getB() {
return b;
}
public void setB(Integer b) {
this.b = b;
}
}
然後我想知道什麼時候a或b發生了變化。我知道javaFX中有一個ObjectProperty。所以我創建對象屬性:
ObjectProperty<Foo> fooProperty = new SimpleObjectProperty<>(new Foo());
然後爲了瞭解A和B場的變化,我添加的ChangeListener:
fooProperty.addListener((observable, oldValue, newValue) -> {
System.out.println("Property changed!");
});
然後實驗:
fooProperty.set(new Foo());
工作好,但下一行:
fooProperty.get().setA(10)
不會調用偵聽器。原因很明顯。最後一行實際上不會更改Foo對象(引用保持不變)。
我有一些可能的解決方案。但他們都不夠優雅。例如,將每個字段更改爲屬性併爲每個變量添加相同的偵聽器。
所以,問題是。添加偵聽器以更改自定義對象字段的方法是什麼?
這難道不是通過將'a'和'b'實現爲'IntegerProperty'並使用固定的'Foo'實例解決的嗎?或者我誤解了這個問題? –