[英]How to populate data in a JComboBox?
I have created a GUI and have a database located externally in which I fetch data from. 我已经创建了一个GUI,并在外部有一个数据库,可以从中获取数据。 I am using the GUI builder in NetBeans to do this.
我正在NetBeans中使用GUI构建器来执行此操作。 Does anyone know of a simple way to populate a jComboBox with values coming from the database?
有谁知道用来自数据库的值填充jComboBox的简单方法吗? When I run the project there are no errors but the combo box remains empty.
当我运行项目时,没有错误,但组合框保持为空。
Here is the code that sets the combo box with the names of discounts: 这是使用折扣名称设置组合框的代码:
public void setDiscountNames(String type, JComboBox cbox) {
cbox.removeAllItems();
ArrayList<Discount> names = new ArrayList<Discount>();
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);
}
}
This is located in a seperate class from the jComboBox object. 它位于与jComboBox对象不同的类中。 This class is called Model.
此类称为模型。
Here is the place I call the setDiscountNames method in a form called DiscountGUIView: 这是我以称为DiscountGUIView的形式调用setDiscountNames方法的地方:
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt){
model.setDiscountNames("Fixed", jComboBox1);
}
Okay (Update) the query does print the results: 好的(更新)查询确实会打印结果:
run:
Travel Standard Fixed Standard BUILD SUCCESSFUL (total time: 1 second) 旅行标准固定标准建造成功(总时间:1秒)
It might be that your SELECT
query returns no results. 您的
SELECT
查询可能未返回任何结果。 To verify this, you can add logging statements inside the while (rs.next())
loop. 为了验证这一点,您可以在
while (rs.next())
循环内添加日志记录语句。 My SQL knowledge is a bit rusty, but I remember using '
(single quotes) for string literals, whereas you use "
(double quotes) in your statement. 我的SQL知识有点生锈,但是我记得对字符串文字使用
'
(单引号),而在语句中使用了"
(双引号)。
Besides that, I see several things which could cause problems: 除此之外,我还看到了可能导致问题的几件事:
The SQL code for PreparedStatement
should not be created by string concatenation. PreparedStatement
的SQL代码不应通过字符串串联创建。 Instead, use ?
而是使用
?
for parameter values which will be substituted into the statement, eg 用于将被替换为语句的参数值,例如
stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?"); stmt.setString(1, type); // first (and only) parameter rs = stmt.executeQuery();
It is strongly recommended that you explicitly close JDBC resources after being done with them. 强烈建议您在使用完JDBC资源后,明确关闭它们。 For this, you need to add a
finally
block after the catch (SQLException ...)
, eg 为此,您需要在
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) {} }
or, preferrably, use the try-with-resources
statement (if you are using Java 7 and higher): 或者,最好使用
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
When trying to add elements dynamically to a combo box, use MutableComboBoxModel.addElement
尝试将元素动态添加到组合框时,请使用
MutableComboBoxModel.addElement
JComboBox box = new JComboBox(new DefaultComboBoxModel());
....
MutableComboBoxModel model = (DefaultComboBoxModel)box.getModel();
while (rs.next()) {
model.addElement(rs.getString("Name"));
}
To remove all elements you could also do 要删除所有元素,您也可以这样做
((DefaultComboBoxModel)box.getModel).removeAllElements();
Using the model methods will fire the necessary changes to update the ui 使用模型方法将触发必要的更改以更新用户界面
EDIT: This is your basic mistake.. you're calling the method in ActionPerformed !! 编辑:这是您的基本错误..您正在ActionPerformed中调用该方法!
classConstructor(){
setDiscountNames("Fixed", jComboBox1); // call this method here.. This will work.
}
If the values are printing correctly then try this.. 如果值打印正确,请尝试此操作。
List<String> strings = new ArrayList<String>();
while(rs.next()){
strings.add(rs.getString("Name")); // Confirm if "Name" is valid
}
cbox.addItem(strings);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.