0

I want to get name and id from database and add it to JCombobox. For this i used

       public void add_Category(JComboBox cmb) {

       try {
            String query = "SELECT * FROM categories";
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {

                String Txtcmb = rs.getString(2).trim();
                int idCmb = rs.getInt("id");
                Item comboItem = new Item(idCmb, Txtcmb); 
                cmb.addItem(comboitem);   //This line add only 1 object in combocox but i have 5 in my database
           }
       } catch(Exception e) {

       }
   }

Item.java

public class Item {
    private int id;
    private String description;

    public Item(int id, String description) {
        this.id = id;
        this.description = description;
    }
    public int getId() {
        return id;
    }

    public String toString() {
        return description;
    }
} 

Now the problem is when I add object into combobox it add only one object while I have 5 object into my database.

It display me only one item in combobox instead of 5. One more thing i want to clear if I add only string into database like comboItem.addItem(Txtcmb); then it works fine

Any idea will be appreciated. Thanks in advance.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
DR Jerry
  • 51
  • 3
  • 11
  • The only reason it would only be adding is because there's only one item coming from the database...or some error occurred while processing the second item, but since you've ignored the exception you wouldn't know – MadProgrammer Sep 09 '14 at 07:03
  • Try to print the `idCmb` and `Txtcmb` and see how many result you got in your resultset. – Deb Sep 09 '14 at 07:07
  • model for JComboBox should be based on Item (incomplete), have to tell ListCellRenderer that to display description (missing there), then selection from JComboBox returns ID, for best of code with good explanation to search in posts by @camickr (tagged by JComboBox) – mKorbel Sep 09 '14 at 07:11
  • as aside then is possible to display two same Item in JComboBox and selection returns proper coordinates d form model, otherwise (bug in DeafultComboBoxModel) isn't possible, selection returns last or near index – mKorbel Sep 09 '14 at 07:13

1 Answers1

0

Thanks to all. Actually i was using Item comboItem[]; before while and and Item comboItem = new Item(idCmb, Txtcmb); inside while. When i remove Item comboItem[]; line and clean and buid my project again then it start working. Again thanks for your concern.

DR Jerry
  • 51
  • 3
  • 11