从数据库获取ID和数据并添加到JCombobox [英] Get Id and data from database and add to JCombobox

查看:209
本文介绍了从数据库获取ID和数据并添加到JCombobox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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;
    }
} 

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

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

它在组合框中仅显示一个项目,而不是5.如果要像comboItem.addItem(Txtcmb);这样仅将字符串添加到数据库中,则我想清除的另一件事是

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.

推荐答案

感谢所有人.实际上我在使用Item comboItem [];在while和Item之前,comboItem = new Item(idCmb,Txtcmb);里面一会儿.当我删除项目comboItem [];排好线,清理并重新招标我的项目,然后它开始工作.再次感谢您的关注.

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.

这篇关于从数据库获取ID和数据并添加到JCombobox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆