无法通过Java

时间:2018-10-05 02:20:05

标签: java database swing 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);
 }

在所有情况下,结果都是相同的

Error in JCombobox

我将非常感谢您提供任何解决问题的信息或资源

2 个答案:

答案 0 :(得分:3)

  

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

achooser.removeAll();

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

您要

achooser.removeAllItems();

从组合框中删除项目。

那条语句应该在循环之外。

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

答案 1 :(得分:1)

我喜欢@camickr的评论,所以要修改我的答案。尝试从结果集中填充模型,然后声明JComboBox:

MutableComboBoxModel model = new DefaultComboBoxModel();
while (rs.next()){ 
    model.addItem(rs.getString("achooserfill"));
}
JComboBox achooser = new JComboBox(model);