编辑ObservableList中的多个元素,仅在最后一次更改后触发更改侦听器
我有一个ObservableList,它不仅在添加或删除元素时触发已注册的ListChangeListener,而且在这些元素内的特定Observable属性发生更改时(例如,一个人员列表,并且当人员的地址发生更改时,将触发ListChangeListeners. 我该如何编辑多个人的地址,并使所有更改一起仅使听众触发一次?
I have an ObservableList that doesn't only trigger the registered ListChangeListeners when elements are added or removed, but also when specific Observable attributes within these elements are changed, e.g. a list of persons and when a person's adress changes, the ListChangeListeners fire. How can I edit the adress of multiple people and have the Listeners only fire once for all changes together?
ObservableList
默认情况下不提供此功能.如果您扩展 ModifiableObservableList
,则可以使其具有beginChange()
和endChange()
功能,可通过外部代码访问.
ObservableList
does not provide this functionality by default. If you extend ModifiableObservableList
though, you could make it's beginChange()
and endChange()
functionality accessible to external code.
尽管正确使用了此类,但您需要小心.如果您不执行相同数量的beginChange
和endChange
调用,则侦听器可能根本不会收到任何更新.
You need to be careful though that this class is used correctly. If you do not do the same number of beginChange
and endChange
calls, the listener may not receive any updates at all.
以下代码不包含有关更新更改的任何实现.我把这个留给你.您需要在beginChange
和endChange
的调用之间使用nextUpdate
.如果需要提取器功能,则可能需要向doXyz
方法添加其他功能以添加侦听器.
The following code does not contain any implementation regarding update changes. I'll leave this up to you. You'll need to use nextUpdate
between calls of beginChange
and endChange
. You may need to add additional functionality to the doXyz
methods to add listeners, if you want that the extractor functionality.
public class BulkEditObservableList<T> extends ModifiableObservableListBase<T> {
private final List<T> backingList;
public BulkEditObservableList(List<T> backingList) {
if (backingList == null) {
throw new IllegalArgumentException();
}
this.backingList = backingList;
}
public BulkEditObservableList() {
this(new ArrayList<>());
}
@Override
public T get(int index) {
return backingList.get(index);
}
@Override
public int size() {
return backingList.size();
}
@Override
protected void doAdd(int index, T element) {
backingList.add(index, element);
}
@Override
protected T doSet(int index, T element) {
return backingList.set(index, element);
}
@Override
protected T doRemove(int index) {
return backingList.remove(index);
}
public void beginBulkChange() {
beginChange();
}
public void endBulkChange() {
endChange();
}
}
用法示例
BulkEditObservableList<Integer> intList = new BulkEditObservableList<>();
intList.addListener((Observable o) -> System.out.println(o));
intList.add(1);
intList.beginBulkChange();
intList.add(2);
intList.add(3);
intList.add(0, 0);
System.out.println("after multi add");
intList.endBulkChange();
输出
[1]
after multi add
[0, 1, 2, 3]