如何在JComboBox中填充数据?

我创建了一个GUI,并在外部有一个数据库,我从中获取数据。 我在NetBeans中使用GUI构建器来执行此操作。 有没有人知道用数据库中的值填充jComboBox的简单方法? 当我运行项目时没有错误,但combobox保持为空。

以下是使用折扣名称设置combobox的代码:

public void setDiscountNames(String type, JComboBox cbox) { cbox.removeAllItems(); ArrayList names = new ArrayList(); try { Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; con = DriverManager.getConnection("jdbc:mysql://localhost:3306/abpp034?user=abpp034&password=120001772"); stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = \"" + type + "\""); rs = stmt.executeQuery(); while(rs.next()){ cbox.addItem(rs.getString("Name")); } } catch (SQLException ex) { Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex); } } 

它位于jComboBox对象的单独类中。 这个类叫做Model。

这是我在名为DiscountGUIView的表单中调用setDiscountNames方法的地方:

 private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt){ model.setDiscountNames("Fixed", jComboBox1); } 

好的(更新)查询会打印结果:

 run: 

旅行标准固定标准BUILD成功(总时间:1秒)

编辑:这是你的基本错误..你在ActionPerformed中调用方法!

 classConstructor(){ setDiscountNames("Fixed", jComboBox1); // call this method here.. This will work. } 

如果值正确打印,请尝试此..

 List strings = new ArrayList(); while(rs.next()){ strings.add(rs.getString("Name")); // Confirm if "Name" is valid } cbox.addItem(strings); 

可能是您的SELECT查询未返回任何结果。 要validation这一点,您可以在while (rs.next())循环内添加日志记录语句。 我的SQL知识有点生疏,但我记得使用' (单引号)表示字符串文字,而你在语句中使用" (双引号) "

除此之外,我看到了一些可能导致问题的事情:

  • 不应通过字符串连接创建PreparedStatement的SQL代码。 相反,使用? 对于将被替换为语句的参数值,例如

     stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?"); stmt.setString(1, type); // first (and only) parameter rs = stmt.executeQuery(); 
  • 强烈建议您在完成JDBC资源后显式关闭它们。 为此,您需要在catch (SQLException ...)之后添加finally块,例如

     } finally { try { if (rs != null) rs.close(); } catch (SQLException ignore) {} try { if (stmt != null) stmt.close(); } catch (SQLException ignore) {} try { if (conn != null) conn.close(); } catch (SQLException ignore) {} } 

    或者,最好使用try-with-resources语句(如果您使用的是Java 7及更高版本):

     try (Connection con = DriverManager.getConnection(...)) { // ... try (PreparedStatement stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?")) { // ... try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { // processing } } } } catch (SQLException) { Logger....; } // notice no finally block; resources are closed automatically 

尝试将元素动态添加到combobox时,请使用MutableComboBoxModel.addElement

 JComboBox box = new JComboBox(new DefaultComboBoxModel()); .... MutableComboBoxModel model = (DefaultComboBoxModel)box.getModel(); while (rs.next()) { model.addElement(rs.getString("Name")); } 

删除所有元素也可以

 ((DefaultComboBoxModel)box.getModel).removeAllElements(); 

使用模型方法将触发必要的更改以更新ui