【发布时间】:2014-08-16 21:48:01
【问题描述】:
我的代码有什么问题?
我正在尝试将数据从 mysql 插入到 netbean 的组合框中
private void btnSandoghMousePressed(java.awt.event.MouseEvent evt) {
try {
String query = "SELECT `AccountType` FROM `account`";
con = Connect.ConnectDB();
PreparedStatement stm = con.prepareStatement(query);
pst = con.prepareStatement(query);
ResultSet rs = pst.executeQuery(query);
ArrayList<String> groupNames = new ArrayList<String>();
while (rs.next()) {
String groupName = rs.getString(4);
groupNames.add(groupName);
}
DefaultComboBoxModel model = new DefaultComboBoxModel(groupNames.toArray());
cmbSemetarID.setModel(model);
rs.close();
} catch (SQLException e) {
System.err.println("Connection Error! it's about date");
}
}
【问题讨论】:
-
模型是否正确填充?
-
是的,模型很好,ArrayList
groupNames = new ArrayList (); -
你试过了吗?
DefaultComboBoxModel model = new DefaultComboBoxModel(); for(String groupname : groupNames) { model.addElement(groupname); }你可以把你的结果一个一个放到comboboxmodel中。也许最好使用 groupNames 的.toArray()方法来初始化 DefaultComboBoxModel。 -
(真的不明白对基础问题的三个赞成票,包含一堆错误,每天在这里问,投票结束)不要在try-catch-中创建任何Java对象(在应用程序中使用的时间更长) finally 块,创建 DefaultComboBoxModel 作为局部变量,在循环内只添加一个新项目,JDBC 应该在 finally 中关闭()否则留在内存中直到当前 JVM 存在
-
btnSandoghMousePressed表示一个按钮。不要将MouseListener用于按钮。请改用ActionListener
标签: java swing jdbc jcombobox comboboxmodel