简体   繁体   中英

Populate a jcombobox in netbeans 7.1

I want to add a combo box which populates from a mysql database in netbeans 7.1.I did a simple implementation like follows, but this coding doesn't work.

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
    try 
    {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/combo","root","root123");
        Statement stmnt = (Statement) con.createStatement();
        String SQL = "SELECT * FROM items";
        ResultSet rs = stmnt.executeQuery(SQL);
        while(rs.next()) 
        {
            jComboBox1.addItem(rs.getString("itemcode"));
        }
    } 
    ...
}

How can I solve this problem.

Let's say your combobox consists of String items. You are to create a combobox which will use these string items in its display.

String items[] = {...};

Sample combobox declaration could be like this:

JComboBox comboBox = new JComboBox(items);

So populating the items array via the data coming from your database could be a solution to your problem, ie combobox has nothing to do with database, but string items have.

int index = 0;
ResultSet rs = statement.executeQuery(SQL);
while(rs.next())
   items[index] = rs.getString("itemcode");

However, since you don't know how many items you will retrieve from the database you can use an arraylist instead of an array so that you can dynamically add items to the list.

try {

    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql:///dbname", "username", "password");
    Statement st=con.createStatement();
    Resultset r=st.executeQuary("SELECT * FROM table name");
     while(r.next()){
        Vector v=new Vector();
        ComboBox1.setModel(new DefaultComboBoxModel(v));
     }

} catch (Exception e) {
    e.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM