简体   繁体   English

JavaFX 绑定和属性更改

[英]JavaFX binding and property change

I'm working in JavaFX with bindings and properties.我在 JavaFX 中使用绑定和属性。 I have a Label label and a Person currentPerson .我有一个Label label和一个Person currentPerson I have the following code:我有以下代码:

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

Then I have in another section of code:然后我在另一段代码中:

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

This way the textProperty of label doesn't update!这样labeltextProperty就不会更新!

But if I do in that section of code:但是,如果我在该部分代码中这样做:

currentPerson.setName(newPerson.getName());

then this updates the textProperty of label .然后这会更新labeltextProperty

My question is: why does the second way update the textProperty of label , while the first doesn't, even though the nameProperty of currentPerson is changed in both cases?我的问题是:为什么第二种方式更新labeltextProperty ,而第一种方式没有,即使currentPersonnameProperty在两种情况下都发生了变化?

I think the most basic answer to your question is that, after the line currentPerson = newPerson;我认为对你的问题最基本的答案是,在currentPerson = newPerson;行之后currentPerson = newPerson; , the currentPerson object is not the same object that was bound to label previously. currentPerson对象与之前绑定到label对象不同。

As mentioned , You've lost your first binding after :如前所述,您在以下情况后丢失了第一个绑定:

currentPerson = newPerson;

The solution is either (re)bind currentPerson after any assignment to currentPerson , or instead, use a method to pass the newPerson data, like:该解决方案是(重)结合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