无法从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);

 }

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

http://img4.mukewang.com/6179ff770001134c03440204.jpg

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


德玛西亚99
浏览 160回答 2
2回答

精慕HU

在所有这些组合框中都没有被清洁。achooser.removeAll();该removeAll()方法是 的方法,而Container不是组合框的方法。你要:achooser.removeAllItems();从组合框中删除项目。并且该语句应该在循环之外。此外,对于这样的事情,您是否甚至验证了您的 ResultSet 包含数据。首先,您应该对数据进行硬编码以证明该addItem()方法有效。然后,一旦您知道逻辑正在运行,您就可以通过从数据库中获取数据来使代码更加动态。

慕桂英546537

我喜欢@camickr 的评论,所以我正在修改我的答案。尝试从结果集中填充模型,然后声明 JComboBox:MutableComboBoxModel model = new DefaultComboBoxModel();while (rs.next()){     model.addItem(rs.getString("achooserfill"));}JComboBox achooser = new JComboBox(model);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java