I'm working in JavaFX with bindings and properties. I have a Label label
and a 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!
But if I do in that section of code:
currentPerson.setName(newPerson.getName());
then this updates the textProperty
of label
.
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?
I think the most basic answer to your question is that, after the line currentPerson = newPerson;
, the currentPerson
object is not the same object that was bound to label
previously.
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.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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.