簡體   English   中英

JavaFX 綁定和屬性更改

[英]JavaFX binding and property change

我在 JavaFX 中使用綁定和屬性。 我有一個Label label和一個Person currentPerson 我有以下代碼:

label.textProperty().bind(currentPerson.nameProperty());

然后我在另一段代碼中:

currentPerson = newPerson;   //newPerson is a given Person instance

這樣labeltextProperty就不會更新!

但是,如果我在該部分代碼中這樣做:

currentPerson.setName(newPerson.getName());

然后這會更新labeltextProperty

我的問題是:為什么第二種方式更新labeltextProperty ,而第一種方式沒有,即使currentPersonnameProperty在兩種情況下都發生了變化?

我認為對你的問題最基本的答案是,在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());
    }
}

您必須設置bindperson's name相關的bind ,因此當您使用getName ,它會更新label

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM