How can I add database id as combobox Index in java?

user1109844 picture user1109844 · Dec 26, 2011 · Viewed 7.4k times · Source

I want to add combobox Index from database id.

 public static void selectCompany(javax.swing.JComboBox cmbCategory ){
    cmbCategory.removeAllItems();
    String sql="SELECT * FROM company_details";
    try{
        Connection conn=dbConnection();
        PreparedStatement pstmt=conn.prepareStatement(sql);
        ResultSet rs=pstmt.executeQuery(sql);
        while(rs.next()){
            int id=rs.getInt("company_id");
            String category=rs.getString("company_name");
            cmbCategory.addItem(id);
            cmbCategory.addItem(category);
        }
    }catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

cmbCategory is combobox object. I want to dispaly id as combobox Index and Combobox list display as category name. Database is mysql.

Answer

Diego Agulló picture Diego Agulló · Dec 26, 2011

You can add objects to the ComboBox, not just strings, so something like this should do the trick:

    while(rs.next()){
        int id=rs.getInt("company_id");
        String category=rs.getString("company_name");
        Object[] itemData = new Object[] {id, category};
        cmbCategory.addItem(itemData);
    }

And as Harry Joy pointed out, you can tell swing how this element should be rendered by using a ListCellRenderer:

class MyListRenderer extends JLabel implements ListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Object[] itemData = (Object[])value;
        setText((String)itemData[1]);

        return this;
    }
}

Which you can later assign to the JComboBox:

cmbCategory.setRenderer(new MyListRenderer());

By doing this, you have the obvious advantage of having both the ID and category name in just one object, so when the user selects an item in the combobox, you can access all the properties of this object (ID and name!).