从数据库获取ID和数据并添加到JCombobox

编程入门 行业动态 更新时间:2024-10-27 03:42:24
本文介绍了从数据库获取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

本文发布于:2023-07-16 07:31:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1119391.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库   数据   ID   JCombobox

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!