Question

I have got this method that fills out my combobox:

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;
}

Then I load it with:

jComboBox2.setModel(con.llenarComboFamilia());

And when I click on "Register" button I have got:

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);

}

But jComboBox2.getSelectedIndex() + 1 does not work for me, becuase I need the ID value from the database, not the selected index.

Any ideas?

Was it helpful?

Solution

you could use a Vector to store the ids. simply populate the vector with id of each item as you add the item to the combobox. The vector and combobox will both have the same number of items so id of item 10 in combobox will be item 10 in vector. then you can get the id of item currently selected on combobox from the vector like vectorIDs.get( jComboBox2.getSelectedIndex () )

OTHER TIPS

Create a custom object to contain both the "Id" and "Description" fields from your SQL query. Then you add this object to the combobox and use a custom renderer.

See Combo Box With Custom Renderer for more information and example code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top