java - 数据未在组合框中显示 - 使用 Netbeans 的 Sql 和 Java

标签 java mysql sql netbeans combobox

我有一个名为“用户”的表,我想在组合框中显示用户类型。我为连接创建了一个单独的类。

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;
}

}

}

我在其上创建组合框的表单具有以下代码。

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                   
}

组合框仍然不显示数据库中的任何值。有人可以告诉我我的代码有什么问题吗?

最佳答案

我一直在努力,终于成功了!我使用了一个名为 fillCombo 的函数,然后调用了它!有效。这就是我喜欢编码的原因,你只需不断尝试,当你最终解决它时,感觉真是太棒了。

现在我必须解决遇到的下一个问题,删除重复值。我会继续努力的!

关于java - 数据未在组合框中显示 - 使用 Netbeans 的 Sql 和 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36699967/

相关文章:

sql - 具有百分比条件的不同 SQL 选择

java - "x cannot be resolved or is not a field"。我怎样才能解决这个问题?加工

Java编译错误无法配置JAVA_HOME

mysql - MySQL 中的一对多关系表

sql - 将数据类型 varchar 转换为 int 时出错

mysql - 在 GROUP BY 中使用 LIMIT 来获得每组 N 个结果?

java - 哪个是 mongodb 访问的最佳 java 驱动程序?

java - 制作可双击的 Jython .jars

mysql - 每次使用不同的用户连接到数据库

javascript - 使用 chartjs 在圆环图中标记问题