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));
}
}
See DefaultComboBoxModel.removeAllElements()
Empties the list.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With