JavaFX ReadOnlyListProperty不是只读的?

JavaFX ReadOnlyListProperty不是只读的?,javafx,Javafx,这段代码抛出一个UnsupportedOperationException,正如我所期望的那样,因为它是只读的 ListProperty<String> lp = new SimpleListProperty<String>(); ReadOnlyListWrapper<String> rolw = new ReadOnlyListWrapper<String>(lp); ReadOnlyListProperty<String> rol

这段代码抛出一个UnsupportedOperationException,正如我所期望的那样,因为它是只读的

ListProperty<String> lp = new SimpleListProperty<String>();
ReadOnlyListWrapper<String> rolw = new ReadOnlyListWrapper<String>(lp);
ReadOnlyListProperty<String> rolp = rolw.getReadOnlyProperty();
rolp.add("element");
ListProperty lp=new SimpleListProperty();
ReadOnlyListWrapper rolw=新的ReadOnlyListWrapper(lp);
ReadOnlyListProperty rolp=rolw.getReadOnlyProperty();
新增(“要素”);
但是,此代码不适用

ObservableList<String> ol = FXCollections.observableArrayList();
ReadOnlyListWrapper<String> rolw = new ReadOnlyListWrapper<String>(ol);
ReadOnlyListProperty<String> rolp = rolw.getReadOnlyProperty();
rolp.add("element");
observeList ol=FXCollections.observearraylist();
ReadOnlyListWrapper rolw=新的ReadOnlyListWrapper(ol);
ReadOnlyListProperty rolp=rolw.getReadOnlyProperty();
新增(“要素”);

这是一个bug,还是我只是不理解什么?

对于提供的示例,最初的期望是错误的。发生UnsupportedOperationException的原因不同,而不是因为“只读”列表正在“写入”。仍然可以有“只读”列表。我希望下面的答案有助于澄清

答案需要分两部分考虑。一个:ListProperty异常和两个:只读列表

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

这个简化的示例也引发了异常。请注意,任何“只读”方面都将被删除:

ListProperty<String> lp = new SimpleListProperty<>();
lp.add("element");
ListProperty lp=new SimpleListProperty();
lp.添加(“要素”);
这可以通过以下方法进行纠正:

ObservableList ol = FXCollections.observableArrayList();
ListProperty<String> lp = new SimpleListProperty<>();
lp.setValue(ol);
lp.add("element");
observeList ol=FXCollections.observearraylist();
ListProperty lp=新的SimpleListProperty();
lp.设定值(ol);
lp.添加(“要素”);
如果我们以类似的方式更改原始示例,那么ListProperty和ObservableList示例都不会抛出异常,这不是OP想要或期望的

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

ObservableList<String> ol = FXCollections.observableArrayList();
ObservableList<String> uol = FXCollections.unmodifiableObservableList(ol);
uol.add("element");
observeList ol=FXCollections.observearraylist();
ObservableList uol=FXCollections.unmodifiableObservableList(ol);
uol.添加(“要素”);
但这并不能回答为什么ReadOnlyListWrapper/属性不这样做的问题

让我们先处理财产问题。ListProperty允许更改值,即允许您为属性分配不同的列表。ReadOnlyListProperty不允许这样做,即,一旦分配了列表,它将保留该列表对象。列表的内容仍然可以更改。以下示例对于ReadOnlyListProperty毫无意义:

ObservableList<String> ol1 = FXCollections.observableArrayList();
ObservableList<String> ol2 = FXCollections.observableArrayList();
ListProperty<String> lp = new SimpleListProperty<>(ol1);
lp.setValue(ol2);
observeList ol1=FXCollections.observearraylist();
ObservableList ol2=FXCollections.observableArrayList();
ListProperty lp=新的SimpleListProperty(ol1);
lp.设定值(ol2);
所以只读是指属性,而不是列表


最后—ReadOnlyListWrapper—正如API文档所述:“此类提供了一个方便的类来定义只读属性。它创建了两个同步的属性。一个属性是只读的,可以传递给外部用户。另一个属性是可读写的,应该只在内部使用。”

感谢您的详细回复。自从我发布这篇文章以来,我花了更多的时间在FX上,并且逐渐了解了你发布的内容。文档仍然有点薄,但正如您所指出的,通过阅读API文档,我至少可以找到部分答案。