Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need help on reset/clear jcombobox values

im using below coding to add values to a jcombobox using another jcombobox and i need to add the values to the jcombobox2 according to the one get selected in the jcombobox1 without appending values so can someone tell me a way to reset or clear the combo-box values when another option selected? below is my coding and i'm new to java and netbeans so if someone can help i'll be grateful :)

    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database1", "root", "senura123");
    Statement stat = (Statement) con.createStatement();
    String val=jComboBox1.getSelectedItem().toString();
    String check; String col;
    if ("Vehicles".equals(val)){
        check = "select reg_no from vehicle;";
        col="reg_no";
    }
    else if ("Travel Guides".equals(val)){
        check = "select username from travelguide;";
        col="username";
    }
    else{
        check = "select username from transportofficer";
        col="username";
    }                   
    ResultSet rslt = stat.executeQuery(check);
    while (rslt.next()) {
        jComboBox2.addItem(rslt.getString(col));                               
    }
 }
like image 218
senrulz Avatar asked Dec 27 '22 02:12

senrulz


2 Answers

See DefaultComboBoxModel.removeAllElements()

Empties the list.

like image 101
Andrew Thompson Avatar answered Jan 30 '23 22:01

Andrew Thompson


Set a new model into your combobox:

final List<String> values = new ArrayList<String>();

while (rslt.next()) {
  values.add(rslt.getString(col));
}

jComboBox2.setModel(new DefaultComboBoxModel(values.toArray()));

See DefaultComboBoxModel.


As a further comment, however, depending on how much latency is involved in your query, you may like to split this work up into EDT and background thread parts using SwingWorker.

like image 36
Greg Kopff Avatar answered Jan 30 '23 21:01

Greg Kopff