【问题标题】:How can I get the ID value from the database when selecting an item from a combobox?从组合框中选择项目时,如何从数据库中获取 ID 值?
【发布时间】:2014-04-28 21:13:14
【问题描述】:

我有这个方法可以填充我的组合框:

public DefaultComboBoxModel llenarComboFamilia() throws SQLException {
    String query = "select * from familias";
    DefaultComboBoxModel df = new DefaultComboBoxModel();
    abrirConexion();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(query);
    while (rs.next()) {
        //df.addElement(rs.getObject("This is the ID I need"));
        df.addElement(rs.getString("String from DB"));
    }
    cerrarConexion();
    return df;
}

然后我加载它:

jComboBox2.setModel(con.llenarComboFamilia());

当我点击“注册”按钮时,我得到了:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    Persona p = new Persona(jTextField7.getText(), 1, 
            jComboBox2.getSelectedIndex() + 1, 
            jTextField5.getText(), jTextField6.getText());

    con.insertarPersonasProp(p);

}

但是jComboBox2.getSelectedIndex() + 1 对我不起作用,因为我需要数据库中的 ID 值,而不是选定的索引。

有什么想法吗?

【问题讨论】:

    标签: java swing jdbc jcombobox listcellrenderer


    【解决方案1】:

    您可以使用 Vector 来存储 id。当您将项目添加到组合框中时,只需使用每个项目的 id 填充向量。向量和组合框都将具有相同数量的项目,因此组合框中项目 10 的 id 将是向量中的项目 10。然后您可以从向量中获取当前在组合框中选择的项目的 ID,例如 vectorIDs.get( jComboBox2.getSelectedIndex ())

    【讨论】:

      【解决方案2】:

      创建一个自定义对象以包含 SQL 查询中的“Id”和“Description”字段。然后将此对象添加到组合框并使用自定义渲染器。

      有关更多信息和示例代码,请参阅Combo Box With Custom Renderer

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2015-10-03
        • 2020-10-13
        • 1970-01-01
        • 2013-12-04
        相关资源
        最近更新 更多