JavaFX, ObservableList: How to fire an InvalidationListener whenever an object of the list gets modified?

笑着哭i 提交于 2020-01-01 19:30:44

问题


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
}

and another class which has a property:

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!"));`.
  }
}

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.


回答1:


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.

EDIT:

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);
        }
    }
});


来源:https://stackoverflow.com/questions/43716022/javafx-observablelist-how-to-fire-an-invalidationlistener-whenever-an-object-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!