JavaFX,ObservableList:每当列表的对象被修改时,如何触发InvalidationListener? [英] JavaFX, ObservableList: How to fire an InvalidationListener whenever an object of the list gets modified?

查看:2670
本文介绍了JavaFX,ObservableList:每当列表的对象被修改时,如何触发InvalidationListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有可观察类 SomeObservableClass 的JavaFX应用程序,其中包含一些属性:

Say I have a JavaFX app with an observable class SomeObservableClass with some Properties:

public class SomeObservableClass{

  private StringProperty prop1 = new SimpleStringProperty();
  private DoubleProperty prop2 = new SimpleDoubleProperty();

  ... constructors, getters and setters
}

另一个具有属性的类:

public class ParentClass{
  private ObservableList<SomeObservableClass> sOC = FXCollections.observableArrayList();`
}

在这个父类我添加一个可观察列表的监听器:`

In this parent class I add a listener for the observable list: `

public class ParentClass{
  private ObservableList<SomeObservableClass> observableList = FXCollections.observableArrayList();

  public`ParentClass(List<SomeObservableClass> list){
    this.observableList.addAll(list);
    this.observableList.addListener((InvalidationListener) observable -> System.out.println("listener detected a change!"));`.
  }
}

现在说在控制器类中我改变了属性其中一个SomeObservableClass对象:

Now say that in a controller class I change the property of one of the SomeObservableClass objects:

public class Controller(){
  private ParentClass parentClass;

  public void changeSomeProps(){
    SomeObservableClass anObservableObject = parentClass.getObservableList().get(0);
    anObservableObject.setProp1("newVal");
  }
}

这不会触发监听器。为什么?

This doesn't fire the listener. Why ?

我怀疑我缺少一些代码让监听器意识到当列表对象的任何属性被修改时它应该触发,但是我我不知道怎么做。

I suspect I am lacking some code to make the listener aware that it should fire when any property of the list objects get modified, but I have no idea how to do that.

推荐答案

默认情况下, ObservableList 不处理项目内容的更改。但是, ObservableList 与提取器的实例化可以处理它们。

By default, ObservableList doesn't handle changes of item's contents. But instanciation of ObservableList with an extractor enables handling them.

ObservableList<SomeObservableClass> observableList = FXCollections.observableArrayList(
            e -> new Observable[]{e.prop1Property(), e.prop2Property()});

// add items and set listeners here

observableList.get(1).setProp1("newVal");
// It fires InvalidationListener and ListChangeListener.






编辑:


似乎只有 ListChangeListener 才能识别更新的项目。请试一试。

It seems only ListChangeListener can identify updated items. Try it out please.

observableList.addListener((ListChangeListener) change -> {
    while (change.next()) {
        if (change.wasUpdated()) {
            SomeObservableClass changedItem = observableList.get(change.getFrom());
            System.out.println("ListChangeListener item: " + changedItem);
        }
    }
});

这篇关于JavaFX,ObservableList:每当列表的对象被修改时,如何触发InvalidationListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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