5

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319

3 Answers3

7

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!).

Diego Agulló
  • 9,298
  • 3
  • 27
  • 41
1

If you want to set company_id as combobox item index then my answer is you can't set item index. If you want to display both, id and category then concatenate ID and company name.

cmbCategory.addItem(id + " " + category);
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • I want to delete selected item how can I do that at that it i required id of the Item –  Dec 26 '11 at 09:36
1

When you use a custom renderer you lose the ability to access the combobox items by using the keyboard to enter the first character of the item. This is because the search of the combobox model uses the toString() method of each item to first the requested item. The toString() implementation of an Array in not meaningul in this case.

A different solution is to create a custom object and override the toString() method of the object as shown in this example: How to use Map element as text of a JComboBox

Community
  • 1
  • 1
camickr
  • 321,443
  • 19
  • 166
  • 288