Get Id and data from database and add to JCombobox

£可爱£侵袭症+ 提交于 2019-12-11 22:58:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/25738472/get-id-and-data-from-database-and-add-to-jcombobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!