2014-06-26 38 views
5

Có gì sai với mã của tôi ở đây?Làm cách nào để chèn dữ liệu từ mysql vào combobox?

Tôi đang cố gắng để chèn dữ liệu từ mysql vào combobox trong 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"); 
    } 
} 
+0

Mô hình có được điền đúng không? – Smutje

+0

Có mô hình là tốt, ArrayList groupNames = new ArrayList (); –

+1

bạn đã thử cái này chưa? 'DefaultComboBoxModel model = new DefaultComboBoxModel(); cho (String groupname: groupNames) { model.addElement (tên nhóm); } ' Bạn có thể đặt kết quả của mình từng cái một vào comboboxmodel. Có lẽ nó là tốt hơn thay vì init DefaultComboBoxModel với phương thức '.toArray()' của groupNames của bạn. – Rubinum

Trả lời

0

Bạn nhận được vấn đề đôi khi bạn cố gắng sử dụng mẫu theo cách này hay cách sử dụng một Vector. Better cố gắng làm một cái gì đó như thế nào,

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

đọc nhận xét của tôi về OP, đăng sai, chống lại tất cả các thực hành tốt – mKorbel

0

Có lẽ phương pháp groupNames.toArray() của bạn không "phù hợp" vào DefaultComboBoxModel() construktor.

Bạn có thể cố gắng để đưa các mục của bạn vào ArrayList của bạn từng người một với điều này:

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

Thats làm thế nào tôi điền comboboxes tôi.

Các vấn đề liên quan