小编Naz*_*ukh的帖子

是否可以创建一个属性来监听 javafx 中自定义对象的更改?

假设我有一个实体类 Foo,其中包含一些字段、getter、setter 和构造函数。例如:

public class Foo {
private Integer a = 0;
private Integer b = 0;

public Foo() {
}

public Integer getA() {
    return a;
}

public void setA(Integer a) {
    this.a = a;
}

public Integer getB() {
    return b;
}

public void setB(Integer b) {
    this.b = b;
}
}
Run Code Online (Sandbox Code Playgroud)

然后我想知道 a 或 b 何时发生变化。我知道 javaFX 中有一个 ObjectProperty。所以我正在创建对象属性:

ObjectProperty<Foo> fooProperty = new SimpleObjectProperty<>(new Foo());
Run Code Online (Sandbox Code Playgroud)

然后为了了解a和b字段的变化,我添加了ChangeListener:

fooProperty.addListener((observable, oldValue, newValue) -> {
    System.out.println("Property changed!");
});
Run Code Online (Sandbox Code Playgroud)

然后实验:

fooProperty.set(new Foo()); …
Run Code Online (Sandbox Code Playgroud)

binding javafx properties object-property

5
推荐指数
1
解决办法
3827
查看次数

标签 统计

binding ×1

javafx ×1

object-property ×1

properties ×1