How do I insert data from mysql into the combobox?

642 Views Asked by At

What's wrong with my code here?

I'm trying to insert data from the mysql into the combobox in 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");
    }
}
2

There are 2 best solutions below

1
On BEST ANSWER

You get problems sometimes you try to use Model this way or using a Vector. Better try to do something like,

  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");
    }
}
0
On

Maybe your groupNames.toArray() method does not "fit" into the DefaultComboBoxModel() construktor.

You can try to put your items into your ArrayList one by one with this:

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

Thats how I fill my comboboxes.