创建可观察列表/集合

我正在尝试在JavaFX 8中创建一个ChoiceBox ,它需要一个Collection 。 我不知道如何创建一个Collection虽然…如果我尝试:

  ObservableList list = new ObservableList(); 

我收到一个错误,说我无法实例化ObservableList因为它是抽象的。 可以理解的。 如果我查看ObservableList的doc,我可以看到SortedList implements ObservableList ,但是我不能这样做:

  ObservableList list = new SortedList(); 

因为没有适用的构造函数。 显然我需要将一个ObservableList传递给SortedList ,这很奇怪,因为我无法创建一个ObservableList

 constructor SortedList.SortedList(ObservableList,Comparator) is not applicable (actual and formal argument lists differ in length) constructor SortedList.SortedList(ObservableList) is not applicable (actual and formal argument lists differ in length) 

我不知道如何解读。 如果我试试

  ObservableList list = new SortedList<SortedList>(); //or ObservableList list = new SortedList<ObservableList>(); 

出于绝望,我得到了一个更复杂的错误。

  SortedList list = new SortedList(); 

也不起作用。 不知何故,这有效(但显然使用不安全的操作):

 ChoiceBox box = new ChoiceBox(FXCollections.observableArrayList("Asparagus", "Beans", "Broccoli", "Cabbage" , "Carrot", "Celery", "Cucumber", "Leek", "Mushroom" , "Pepper", "Radish", "Shallot", "Spinach", "Swede" , "Turnip")); 

所以我尝试过:

  ObservableList list = new FXCollections.observableArrayList("Asparagus", "Beans", "Broccoli", "Cabbage" , "Carrot", "Celery", "Cucumber", "Leek", "Mushroom" , "Pepper", "Radish", "Shallot", "Spinach", "Swede" , "Turnip"); 

但也没有运气。 我非常困惑,在无休止的循环中一遍又一遍地尝试理解这一点。 我发现的文档显示了没有帮助的示例,或者没有示例。 官方文档也没用:

例如,假设您有一个Collection c,它可以是List,Set或其他类型的Collection。 这个习惯用法创建一个新的ArrayList(List接口的一个实现),最初包含c中的所有元素。

  List list = new ArrayList(c); 

所以要创建ArrayList的实现,我需要有一个List 。 我之前首先阅读文档的原因是为了学习如何制作我们所拥有的东西。 我迷路了。 帮帮我?

使用FXCollections的工厂方法:

 ObservableList list = FXCollections.observableArrayList(); 

选择框构造函数中的不安全操作是因为您没有为选择框指定类型:

 ChoiceBox box = new ChoiceBox<>(FXCollections.observableArrayList("Asparagus", "Beans", "Broccoli", "Cabbage" , "Carrot", "Celery", "Cucumber", "Leek", "Mushroom" , "Pepper", "Radish", "Shallot", "Spinach", "Swede" , "Turnip")); 

SortedList的错误是因为没有构造函数不带参数。 (再次,请参阅javadoc 。)有两个构造函数:最简单的构造函数引用一个ObservableList (排序列表将为其提供排序视图的列表)。 所以你需要类似的东西

 SortedList sortedList = new SortedList<>(list); 

要么

 SortedList sortedList = new SortedList<>(FXCollections.observableArrayList());