在表中进行编辑是否会按预期更新基础集?
不,因为,您正在复制集合:
new ArrayList<E>(pojo.getObservableSet())
是这样做的“正确”方法吗?
我认为正确的方法是不这样做。
Set不是
List,反之亦然。两者都有特定的矛盾。例如,列表是有序的,并且集合不包含重复的元素。
而且,也
FXCollections都没有
Bindings提供这种东西。
我希望将集合保留为一组以强制执行唯一性
我想您可以编写一个custom
ObservableList,例如
Parent::children具有类似的行为。
IllegalArgumentException如果添加了重复的子项,则抛出。如果您查看源代码,将会看到它是一个
VetoableListDecorator扩展。您可以编写自己的:
import java.util.HashSet;import java.util.List;import java.util.Set;import javafx.collections.FXCollections;import javafx.collections.ObservableList;import com.sun.javafx.collections.VetoableListDecorator;public class CustomObservableList<E> extends VetoableListDecorator<E> { public CustomObservableList(ObservableList<E> decorated) { super(decorated); } @Override protected void onProposedChange(List<E> toBeAdded, int... indexes) { for (E e : toBeAdded) { if (contains(e)) { throw new IllegalArgumentException("Duplicament element added"); } } }}class Test { public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object(); Set<Object> set = new HashSet<Object>(); set.add(o1); CustomObservableList<Object> list = new CustomObservableList<Object>(FXCollections.observableArrayList(set)); list.add(o2); list.add(o1); // throw Exception }}


