When observablelist generate update change event?

耗尽温柔 提交于 2019-12-22 05:52:34

问题


I tried different collections under different conditions but all changes that I was able to receive were Permutation, Add, Removed and Replace changes.

In what conditions does update change emerge? What base class, what stored class and what operations is needed to produce such event?


回答1:


To generate an update event, you must create an ObservableList with an extractor.

The extractor is a function mapping each element in the list to an array of Observables. If any of those Observables change (while the element is still in the list), then the list will receive an update event.

For example, given a Person class:

public class Person {
    private final StringProperty name = new SimpleStringProperty();

    public Person(String name) {
        nameProperty().set(name);
    }

    public StringProperty nameProperty() {
        return name ;
    }
    public final String getName() {
        return nameProperty().get();
    }
    public final void setName(String name) {
        nameProperty().set(name);
    }
}

if you create an observable list as

ObservableList<Person> people = FXCollections.observableArrayList(person -> 
    new Observable[] {person.nameProperty()} );

and register a listener

people.addListener((Change<? extends Person> change) -> {
    while (change.next()) {
        if (change.wasAdded()) {
            System.out.println("Add");
        }
        if (change.wasUpdated()) {
            System.out.println("Update");
        }
    }
});

Then the following will show an update event:

Person person = new Person("Jacob Smith");
people.add(person);
person.setName("Isabella Johnson");


来源:https://stackoverflow.com/questions/27517082/when-observablelist-generate-update-change-event

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