2016-04-18 9 views
0

Ich habe eine Tabelle namens "Benutzer", aus dem ich die Benutzertypen in einer Combo-Box anzeigen möchte. Ich habe eine separate Klasse für die Verbindung erstellt.Daten nicht in Combobox - Sql und Java mit Netbeans

package testdb; 
import java.sql.*; 
import javax.swing.*; 


public class MySqlConnect { 
Connection conn = null; 
public static Connection ConnectDB(){ 
    try{ 
     Class.forName("com.mysql.jdbc.Driver"); 
     Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", ""); 
     JOptionPane.showMessageDialog(null, "Connected to database"); 
     return conn; 

} 
catch (Exception e){ 
JOptionPane.showMessageDialog(null, e); 
return null; 
} 

} 

} 

Das Formular, auf dem ich das Kombinationsfeld erstellt habe, hat den folgenden Code.

package testdb; 

import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import javax.swing.JOptionPane; 


public class Combo extends javax.swing.JFrame { 
    Connection conn = null; 
    PreparedStatement pst = null; 
    ResultSet rs = null; 


public Combo() { 
    initComponents(); 
} 

private void initComponents() { 

    jLabel1 = new javax.swing.JLabel(); 
    combo1 = new javax.swing.JComboBox<>(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    jLabel1.setText("User Type"); 

    combo1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); 
    combo1.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      combo1ActionPerformed(evt); 
     } 
    }); 

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(41, 41, 41) 
      .addComponent(jLabel1) 
      .addGap(73, 73, 73) 
      .addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap(181, Short.MAX_VALUE)) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(43, 43, 43) 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
       .addComponent(jLabel1) 
       .addComponent(combo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
      .addContainerGap(237, Short.MAX_VALUE)) 
    ); 

    pack(); 
}// </editor-fold>       

private void combo1ActionPerformed(java.awt.event.ActionEvent evt) {          
    // TODO add your handling code here: 

    try{ 
     conn = MySqlConnect.ConnectDB(); 
     String s = "Select * from user"; 
     pst = conn.prepareStatement(s); 
     rs = pst.executeQuery(); 

     while(rs.next()){ 
      String cb = rs.getString("username"); 
      combo1.addItem(cb); 
     } 
    } 
    catch (Exception e){ 
     JOptionPane.showMessageDialog(null, e); 
    } 
}          

/** 
* @param args the command line arguments 
*/ 
public static void main(String args[]) { 
    /* Set the Nimbus look and feel */ 
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
    */ 
    try { 
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (ClassNotFoundException ex) { 
     java.util.logging.Logger.getLogger(Combo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(Combo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(Combo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(Combo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 

    /* Create and display the form */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new Combo().setVisible(true); 
     } 
    }); 
} 

// Variables declaration - do not modify      
private javax.swing.JComboBox<String> combo1; 
private javax.swing.JLabel jLabel1; 
// End of variables declaration     
} 

Das Kombinationsfeld zeigt immer noch keine Werte aus der Datenbank an. Könnte mir bitte jemand sagen, was in meinem Code nicht stimmt?

Antwort

0

Ich habe es versucht und endlich verstanden! Ich benutzte eine Funktion namens fillCombo und nannte sie dann! Es funktionierte. Das ist es, was ich am Kodieren liebe, du musst es einfach weiter probieren, wenn du es schließlich löst, es fühlt sich einfach unglaublich an.

Jetzt muss ich das nächste Problem lösen, das ich angetroffen habe, doppelte Werte zu entfernen. Ich werde es weiter versuchen!

Verwandte Themen