[英]JavaFX binding and property change
我在 JavaFX 中使用綁定和屬性。 我有一個Label label
和一個Person currentPerson
。 我有以下代碼:
label.textProperty().bind(currentPerson.nameProperty());
然后我在另一段代碼中:
currentPerson = newPerson; //newPerson is a given Person instance
這樣label
的textProperty
就不會更新!
但是,如果我在該部分代碼中這樣做:
currentPerson.setName(newPerson.getName());
然后這會更新label
的textProperty
。
我的問題是:為什么第二種方式更新label
的textProperty
,而第一種方式沒有,即使currentPerson
的nameProperty
在兩種情況下都發生了變化?
我認為對你的問題最基本的答案是,在currentPerson = newPerson;
行之后currentPerson = newPerson;
, currentPerson
對象與之前綁定到label
對象不同。
如前所述,您在以下情況后丟失了第一個綁定:
currentPerson = newPerson;
該解決方案是(重)結合currentPerson
任何分配到后currentPerson
,或相反,使用一種方法來傳遞newPerson
數據,如:
currentPerson.setPerson(newPerson);
public class Person{
private StringProperty name = new SimpleStringProperty();
// ....
public void setPerson(Person person) {
// ....
this.name.set(person.name.get());
}
}
您必須設置bind
該person's name
相關的bind
,因此當您使用getName
,它會更新label
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.