如何在jComboBox中检索绑定到数据库表中的对象并将其存储到另一个表

时间:2018-10-02 03:24:10

标签: java swing netbeans jcombobox

我在数据库中创建了一个名为“ model”和“ item”的表。并创建了Model()和Item()类。 对于表 “模型”,它具有以下字段:model_ID和model_description。对于表“ item”:item_ID,item_description,model_ID。

通过使用Netbeans 8.2绑定表“ model”和jComboBox,我能够在jComboBox中显示model_description。

现在我要做的是将jComboBox中的选定项目存储到“项目”表中。

我尝试了以下代码:

Session session = NewHibernateUtil.getSessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Model model = (Model) session.get(Model.class, jComboBox.getSelectedIndex+1);
Item item = new Item();
item.setDescription(description);
item.setModel(model);
session.save(item);
transaction.commit();
session.close();

此代码的问题是,如果我将jComboBox中的model_description显示按升/降序排序,它将不会返回正确的对象。

是否可以将所选项目直接存储在jComboBox中作为模型对象?

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

  

通过使用Netbeans 8.2绑定表“ model”和jComboBox,我能够在jComboBox中显示model_description。

我不知道Netbeans绑定是做什么的,但这似乎不是一个好的解决方案。如果您从Netbeans平台移走怎么办?您的代码将如何工作?或者将来您将如何做?

相反,我建议您可以在JComboBox中存储自定义对象。因此,您可以将Item对象存储在组合框中,然后创建一个自定义渲染器,以在组合框中显示“说明”。

当您只需要选择的项目时:

comboBox.getSelectedItem() 

,您就可以访问Item对象及其所有属性。

自定义渲染器如下所示:

class FooRenderer extends BasicComboBoxRenderer
{
    public Component getListCellRendererComponent(
        JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
    {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        if (value instanceof Foo)
        {
            Foo foo = (Foo)value;
            setText( foo.getDescription() );
        }

        return this;
    }
}

将“ Foo”对象替换为“ Item”对象。

但是,当您使用自定义渲染器时,您将中断组合框,因为您将不再能够使用键盘通过键入项目描述的第一个字符来选择项目。有关此问题和解决方案的更多信息,请参见Combo Box With Custom Renderer

相关问题