JavaFX ObservableList的事件监听(ObservableSet、ObservableMap使用类似)

104 篇文章 5 订阅

一、什么是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方法,依次获取触发的事件并处理。

二、监听类型

从上面的代码中,我们可以看到有几个分支条件,每个分支就是数据发生了某种改变,基本的有三种情况:

  1. List排列顺序改变
  2. List中的数据发生改变(数据更新)
  3. 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值