JavaFX绑定和属性更改 [英] JavaFX binding and property change

查看:202
本文介绍了JavaFX绑定和属性更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaFX中使用绑定和属性. 我有一个Label labelPerson 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

这样labeltextProperty不会更新!

但是,如果我在那部分代码中这样做:

But if I do in that section of code:

currentPerson.setName(newPerson.getName());

然后将更新labeltextProperty.

我的问题是:为什么第二种方法更新labeltextProperty,而第一种方法却没有,即使在两种情况下都更改了currentPersonnameProperty?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆