0

我想从数据库中获取名称和 ID 并将其添加到JCombobox. 为此我使用

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

       }
   }

项目.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;
    }
} 

现在的问题是,当我将对象添加到组合框中时,它只添加一个对象,而我的数据库中有 5 个对象。

它只在组合框中显示一个项目而不是 5 个。如果我只将字符串添加到数据库中,我还想清除一件事,这样comboItem.addItem(Txtcmb);它就可以正常工作

任何想法将不胜感激。提前致谢。

4

1 回答 1

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.

于 2014-09-09T07:15:42.420 回答