【问题标题】:How do I insert data from mysql into the combobox?如何将 mysql 中的数据插入到组合框中?
【发布时间】: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


【解决方案1】:

有时您尝试以这种方式使用模型或使用Vector 时会遇到问题。最好尝试做类似的事情,

  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);
        DefaultComboBoxModel model = new DefaultComboBoxModel();
        while (rs.next()) { 
            String groupName = rs.getString(4); 
            model.add(groupName);
        } 

        cmbSemetarID.setModel(model);
        rs.close();    
    } catch (SQLException e) {
    System.err.println("Connection Error! it's about date");
    }
}

【讨论】:

  • 阅读我对 OP 的评论,错误的帖子,违反了所有好的做法
【解决方案2】:

也许您的 groupNames.toArray() 方法不“适合”到 DefaultComboBoxModel() 构造函数中。

您可以尝试将您的项目一一放入您的 ArrayList 中:

DefaultComboBoxModel model = new DefaultComboBoxModel();
for(String groupname : groupNames) 
{
  model.addElement(groupname);
}
cmbSemetarID.setModel();

这就是我填充组合框的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多