如何使用数据库中的数据填充JavaFX ChoiceBox?

private void initialize() { loadPersistenceContext(); List events = getEventsChoiceBox(getPersistenceContext()); ObservableList data = FXCollections.observableList(events); cbEvent.setItems(data); // Inserting data into the ChoiceBox } 

这是我的主要代码。 问题是当表单被加载时,我得到了在ChoiceBox中插入的对象而不是属性。

这是我的列表事件的内容

 Object[] |- String |- Integer Object[] |- String |- Integer 

所以我想要一个带有String属性的ChoiceBox,并且Integer映射到我的控制器。

我尝试了很多东西,但无法理解。

请参阅由数据库ID支持的JavaFX ChoiceBox控件的此示例。

该示例的工作原理是定义一个Choice类,该类由数据库行ID和要在“选择”框中显示的项的字符串表示组成。 使用自定义实现覆盖Choice的默认toString方法,该实现返回要显示的项的字符串表示forms,而不是数据库ID。 将选项添加到ChoiceBox时,ChoiceBox会将每个Choice转换为字符串以供显示。 Choice的显示字符串值只是选择文本,而不是包括数据库ID或使用仅显示无意义对象引用的默认toString of Choice。

选择框示例应用的输出:

选择框示例应用程序的输出

还要考虑一个ComboBox用于这样的实现,因为它内置了一些机制来从节点的显示中抽象出节点的值(通过CellFactory )。 然而,使用ComboBox通常比ChoiceBox更复杂。

这是来自forums.oracle.com的另一个简单实现

为键值创建一个类

 public class KeyValuePair { private final String key; private final String value; public KeyValuePair(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public String toString() { return value; } } 

然后创建ChoiceBox为:

 ChoiceBox choiceBox = new ChoiceBox(); 

填充元素;

 choiceBox .getItems().add(new KeyValuePair("1", "Active")); 

提示:将数据库中的键值对重新转换为ArrayList并进行迭代

要检索值:

 choiceBox.getValue().getKey(); // returns the "1" choiceBox.getValue().toString(); // returns the "Active" 

或者简单地执行: myChoiceBox.setConverter(myStringConverter) ,传入您自己的javafx.util.StringConverter ( JavaDoc )子类的实例。

覆盖toString(和fromString)使您可以完全控制对象的显示方式,而无需在对象本身中实现toString