如何使用数据库中的数据填充JavaFX ChoiceBox? [英] How do I populate a JavaFX ChoiceBox with data from the Database?

查看:193
本文介绍了如何使用数据库中的数据填充JavaFX ChoiceBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  private void initialize(){
loadPersistenceContext();

列表<事件> events = getEventsChoiceBox(getPersistenceContext());
ObservableList<事件> data = FXCollections.observableList(events);

cbEvent.setItems(data); //将数据插入ChoiceBox
}

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



这是我的列表事件的内容

  Object [] 
| - String
| - Integer
Object []
| - String
| - 整数

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



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

解决方案

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


private void initialize() {
    loadPersistenceContext();

    List<Events> events = getEventsChoiceBox(getPersistenceContext());
    ObservableList<Event> data = FXCollections.observableList(events);

    cbEvent.setItems(data); // Inserting data into the ChoiceBox
}

This is my main code. Problem is when the form is loaded, I get the Objects inserted in the ChoiceBox and not the properties.

This is the content of my List Events

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

So I want a ChoiceBox with that String property showing up and the Integer mapped to my controller.

I tried a lot of things but couldn't figure it out.

解决方案

See this example of a JavaFX ChoiceBox control backed by Database IDs.

The example works by defining a Choice class consisting of a database row ID and a string representation of the item to be displayed in the Choice box. The default toString method of Choice is overridden with a custom implementation that returns a string representation of the item to be displayed and not the database ID. When you add the choices to the ChoiceBox, the ChoiceBox will convert each Choice into a string for display. The displayed string value of the Choice is just the choice text rather than also including the database ID or using the default toString of Choice that would just display a meaningless object reference.

Output of choicebox sample app:

Also consider a ComboBox for such an implementation, as it has a mechanisms built into it to abstract the values of nodes from the display of the nodes (via a CellFactory). Use of a ComboBox is however often more complex than a ChoiceBox.

这篇关于如何使用数据库中的数据填充JavaFX ChoiceBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆