JavaFX绑定和属性更改 [英] JavaFX binding and property change
问题描述
我在JavaFX中使用绑定和属性.
我有一个Label label
和Person currentPerson
.
我有以下代码:
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
这样label
的textProperty
不会更新!
但是,如果我在那部分代码中这样做:
But if I do in that section of code:
currentPerson.setName(newPerson.getName());
然后将更新label
的textProperty
.
我的问题是:为什么第二种方法更新label
的textProperty
,而第一种方法却没有,即使在两种情况下都更改了currentPerson
的nameProperty
?
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?
推荐答案
如上所述,您已经失去了第一个绑定:
As mentioned, You've lost your first binding after :
currentPerson = newPerson;
解决方案是在对currentPerson
进行任何赋值后将(c)绑定(重新)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());
}
}
这篇关于JavaFX绑定和属性更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!