JavaFX ReadOnlyListProperty不是只读的吗?

Tim*_*her 5 javafx

此代码抛出UnsupportedOperationException,正如我所期望的那样,因为它是只读的.

ListProperty<String> lp = new SimpleListProperty<String>();
ReadOnlyListWrapper<String> rolw = new ReadOnlyListWrapper<String>(lp);
ReadOnlyListProperty<String> rolp = rolw.getReadOnlyProperty();
rolp.add("element");
Run Code Online (Sandbox Code Playgroud)

但是,这段代码没有.

ObservableList<String> ol = FXCollections.observableArrayList();
ReadOnlyListWrapper<String> rolw = new ReadOnlyListWrapper<String>(ol);
ReadOnlyListProperty<String> rolp = rolw.getReadOnlyProperty();
rolp.add("element");
Run Code Online (Sandbox Code Playgroud)

这是一个错误,还是我只是不理解某些东西?

Nig*_*Eke 9

最初的期望是错误的 - 对于提供的示例.UnsupportedOperationException由于其他原因而发生,而不是因为"只读"列表被"写入".仍然可以使用"只读"列表.我希望下面的答案有助于澄清.

答案需要分为两部分.一:ListProperty异常和两个:只读列表.

1)ListProperty示例失败,因为没有为该属性分配列表.

这个简化的示例也引发了异常.请注意,删除了任何"只读"方面:

ListProperty<String> lp = new SimpleListProperty<>();
lp.add("element");
Run Code Online (Sandbox Code Playgroud)

这可以通过以下方式纠正:

ObservableList ol = FXCollections.observableArrayList();
ListProperty<String> lp = new SimpleListProperty<>();
lp.setValue(ol);
lp.add("element");
Run Code Online (Sandbox Code Playgroud)

如果我们以类似的方式更改原始示例,那么ListProperty和ObservableList示例都不会抛出异常,这不是OP想要或期望的.

2)第二部分询问为什么可以将元素添加到只读列表中.使用FXCollections.unmodifiableObservableList创建只读列表将按预期抛出UnsupportedOperationException:

ObservableList<String> ol = FXCollections.observableArrayList();
ObservableList<String> uol = FXCollections.unmodifiableObservableList(ol);
uol.add("element");
Run Code Online (Sandbox Code Playgroud)

但这并没有回答为什么ReadOnlyListWrapper/Property没有这样做的问题?

让我们首先处理该物业.ListProperty允许更改,即它允许您为属性分配不同的列表.ReadOnlyListProperty不允许这样做,即一旦分配了列表,它就是该列表对象.列表的内容仍然可以更改.以下示例对ReadOnlyListProperty没有意义:

ObservableList<String> ol1 = FXCollections.observableArrayList();
ObservableList<String> ol2 = FXCollections.observableArrayList();
ListProperty<String> lp = new SimpleListProperty<>(ol1);
lp.setValue(ol2);
Run Code Online (Sandbox Code Playgroud)

因此只读是指属性,而不是列表.

最后 - ReadOnlyListWrapper - 正如API文档所述"这个类提供了一个方便的类来定义只读属性.它创建了两个同步的属性.一个属性是只读的,可以传递给外部用户.另一个属性是读取 - 可写,只能在内部使用."