一、什么是ObservableList?
ObservableList是继承了Observable接口的List列表。
官方介绍:A list that allows listeners to track changes when they occur. Implementations can be created using methods in FXCollections
such as observableArrayList
, or with a SimpleListProperty
.
可以通过给ObservableList列表注册事件监听器,监听列表内容的改变。ObservableList列表继承Observable接口,可以注册InvalidationListener监听器,列表本身也通过addListener方法注册ListChangeListener.Change监听器。
注册ListChangeListener.Change监听器:
// 伪码// 创建列表,注册监听器。
ObservableList<Person> observableList = FXCollections.observableArrayList();// Register changed listener and invalidated listener.
observableList.addListener(SimpleListChangeTest01::onChanged);......// 监听器
public static void onChanged(ListChangeListener.Change<? extends Person> personChange) {while (personChange.next()) {/*** 注意change的事件序列。wasReplaced事件由wasRemoved和wasAdded两个事件组合而成,所以将* wasReplaced事件在wasRemoved和wasAdded事件之前处理。*/if (personChange.wasPermutated()) {System.out.println("List was permutated: " + personChange);} else if (personChange.wasUpdated()) {System.out.println("List was updated : " + personChange);} else if (personChange.wasReplaced()) {System.out.println("List was replaced : " + personChange);} else {if (personChange.wasAdded()) {System.out.println("List was added : " + personChange);} else if (personChange.wasRemoved()) {System.out.println("List was removed : " + personChange);}}}
}
通过调用next方法,依次获取触发的事件并处理。
二、监听类型
从上面的代码中,我们可以看到有几个分支条件,每个分支就是数据发生了某种改变,基本的有三种情况:
- List排列顺序改变
- List中的数据发生改变(数据更新)
- List的数据添加及删除(数据新增或删除)
官方文档说明监听顺序为:permutated、add/remove、update。
in case the change contains multiple changes of different type, these changes must be in the following order: permutation change(s), add or remove changes, update changes. This is because permutation changes cannot go after add/remove changes as they would change the position of added elements. And on the other hand, update changes must go after add/remove changes because they refer with their indexes to the current state of the list, which means with all add/remove changes applied.