Search code examples
javamysqljcombobox

How to auto refresh jComboBox data after update?


I have a jComboBox that getting data from MySQL server database.

When I add new data to database, the jComboBox doesn't show it, and I must reopen my program to add the new data to jComboBox.

How can I refresh jComboBox data automatically?

This is my code :

private void dataComboBox(){
    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
        Statement stat = con.createStatement();
        String sql = "select id from perfume order by id asc";      
        ResultSet res = stat.executeQuery(sql);                             
        while(res.next()){
            Object[] ob = new Object[3];
            ob[0] = res.getString(1);
            jComboBox5.addItem(ob[0]);                                     
        }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
    }
}


private void showCBdata(){
    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
        Statement stat = con.createStatement();
        String sql = "select name from perfume where id='"+jComboBox5.getSelectedItem()+"'";  
        ResultSet res = stat.executeQuery(sql);

    while(res.next()){
        Object[] ob = new Object[3];
        ob[0]=  res.getString(1);            
        jTextField8.setText((String) ob[0]);
    }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}


//call method
private void jComboBox5ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    showCBdata();
}

can you help me?

thank you..


Solution

  • You can do it in this way it will automatically refresh the combobox

    try {
                comboBox.removeAllItems();
    
                sql = "SELECT * FROM `table_name`";
                rs = stmnt.executeQuery(sql);
    
            while (rs.next()) {
                String val = rs.getString("column_name");
                comboBox.addItem(val);
            }
        } catch (SQLException ex) {
            Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
        }
    

    removeAllItems(); method will clean the combobox to insure that not to repeat values.
    You do not need to create a separate Object to add in jComboBox instead you can add String too.