gpt4 book ai didi

javafx - 如何使用 Set 作为 TableView 的基础

转载 作者:行者123 更新时间:2023-12-02 03:14:31 25 4
gpt4 key购买 nike

我已经开发了一些代码,并且我有一组用户:

public class ParkCentral{
private Set<User> users = new HashSet<>();
}

然后,在另一个类中,我正在开发一个 GUI 和一个 User 的 TableView。问题是我无法从 Set 创建 ObervableList。我希望 ParkCentral.users 的更改能够反射(reflect)在 TableView 上。

是否可以在不更改 ParkCentral 实现、不将 Set 更改为 List 的情况下执行此操作?

为什么 TableView 只能与 ObservableList 配合使用,而不能与 ObservableSet 或 ObservableMap 配合使用?

最佳答案

Why TableView only works with ObservableList and not with ObservableSet or ObservableMap?

TableView 呈现有序的项目集合。都不是 map Set 也不满足这些要求(某些实现除外)。

不过,可以监听Set中的更改并在List中进行适当的更改。不过,仅使用 HashSet 是不可能实现这一点的;根本没有办法观察这个集合;进行更改后,您始终需要手动更新列表。

使用 ObservableSet 相反,您可以添加一个对列表进行更新的监听器。

public class SetContentBinding<T> {

private final ObservableSet<T> source;
private final Collection<? super T> target;
private final SetChangeListener<T> listener;

public SetContentBinding(ObservableSet<T> source, Collection<? super T> target) {
if (source == null || target == null) {
throw new IllegalArgumentException();
}
this.source = source;
this.target = target;
target.clear();
target.addAll(source);
this.listener = c -> {
if (c.wasAdded()) {
target.add(c.getElementAdded());
} else {
target.remove(c.getElementRemoved());
}
};
source.addListener(this.listener);
}

/**
* dispose the binding
*/
public void unbind() {
source.removeListener(listener);
}

}

使用示例:

public class ParkCentral{
private ObservableSet<User> users = FXCollections.observableSet(new HashSet<>());
}
new SetContentBinding(parkCentral.getUsers(), tableView.getItems());

关于javafx - 如何使用 Set 作为 TableView 的基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56576565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com