如何在JComboBox中填充数据? [英] How to populate data in a JComboBox?
问题描述
我创建了一个GUI并在外部放置了一个数据库,从中可以从中获取数据.我正在NetBeans中使用GUI构建器来执行此操作.有谁知道用来自数据库的值填充jComboBox的简单方法吗?当我运行项目时,没有错误,但是组合框保持为空.
I have created a GUI and have a database located externally in which I fetch data from. I am using the GUI builder in NetBeans to do this. Does anyone know of a simple way to populate a jComboBox with values coming from the database? 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);
}
}
这与jComboBox对象位于不同的类中.此类称为模型.
This is located in a seperate class from the jComboBox object. This class is called Model.
在这里我以一种名为DiscountGUIView的形式调用setDiscountNames方法:
Here is the place I call the setDiscountNames method in a form called DiscountGUIView:
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt){
model.setDiscountNames("Fixed", jComboBox1);
}
好的(更新)查询确实会打印结果:
Okay (Update) the query does print the results:
run:
旅行标准 固定标准 建立成功(总时间:1秒)
Travel Standard Fixed Standard BUILD SUCCESSFUL (total time: 1 second)
推荐答案
这是您的基本错误.
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);
这篇关于如何在JComboBox中填充数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!