首页 > 解决方案 > 无法从java中的数据库填充Jcombobox

问题描述

我正在尝试从数据库中获取信息以填充 Jcombobox,我正在尝试使用以下代码,但它们不起作用,在所有这些代码中,组合框都没有被清理。

第一次尝试

try {
                    con = Connectionz.getConnection();//Connection Object 
                    pst = con.prepareStatement("SELECT * AS achooserfill FROM Login_Users WHERE [C Team Lead] =?");
                    pst.setString(1, va);
                    rs = pst.executeQuery();

                    while (rs.next()) {
                        achooser.removeAll();
                        achooser.addItem("Please select agent");
                        achooser.addItem(rs.getString("achooserfill"));

           }
     }catch(Exception e){
         System.err.println(e);
     }

第二次尝试

 try {
                con = Connectionz.getConnection();//Connection Object 
                pst = con.prepareStatement("SELECT * FROM Login_Users WHERE [C Team Lead] =?");
                pst.setString(1, va);
                rs = pst.executeQuery();

                while (rs.next()) {
                    achooser.removeAll();
                    achooser.addItem("Please select agent");
                    achooser.addItem(rs.getString("[VA #]"));

       }
 }catch(Exception e){
     System.err.println(e);
 }

第三次尝试

 try {
                con = Connectionz.getConnection();//Connection Object 
                pst = con.prepareStatement("SELECT [VA #] FROM Login_Users WHERE [C Team Lead] =?");
                pst.setString(1, va);
                rs = pst.executeQuery();

                while (rs.next()) {
                    achooser.removeAll();
                    achooser.addItem("Please select agent");
                    achooser.addItem(rs.getString("[VA #]"));

       }
 }catch(Exception e){
     System.err.println(e);
 }

在所有情况下,结果都是一样的,

JCombobox 中的错误

我真的很感激任何类型的信息或任何资源来解决这种情况

标签: javadatabaseswingjcombobox

解决方案


在所有这些中,组合框都没有被清理。

achooser.removeAll();

removeAll()方法是 的方法,而Container不是组合框。

你要:

achooser.removeAllItems();

从组合框中删除项目。

该语句应该在循环之外。

此外,对于这样的事情,您甚至验证您的 ResultSet 是否包含数据。首先,您应该对数据进行硬编码以证明该addItem()方法有效。然后,一旦您知道逻辑正在运行,您就可以通过从数据库中获取数据来使代码更加动态。


推荐阅读