Reputation: 127
I have made a combobox which is being filled up with the database entries. The problem that i'm currently facing is that when I write "H" the list gets filled with all the names starting with "H" as required but the first name in the list automatically gets selected. How to avoid this problem?
String ch = text.getText();
if (ch.equals("")) {
combo.setVisible(false);
} else {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/userlogin", "root","12345");
Statement st = connect.createStatement();
ResultSet rs = st.executeQuery("SELECT author_name FROM scrpd_authors WHERE author_name LIKE '"+ ch + "%'");
while (rs.next()) {
String name = rs.getString("author_name");
if (name.equals("")) {
searchitems.addItem("");
} else {
searchitems.addItem(rs.getString("author_name"));
searchitems.setVisible(true);
}
}
connect.close();
} catch (Exception ex) {
}
}
Please note the combobox is being filled with all my desired entries based on the mysql query, the problem is just with the selection of the first entry by itself.
Upvotes: 0
Views: 3892
Reputation: 51525
that's a quirk of the not-editable JComboBox when adding to an empty box:
addItem(item)
will select that iteminsertItemAt(item, 0)
will not select that itemThat quirk is independent on whether the filling happens on the model or on the view-
So if deselecting after filling the model (as suggested by Rob) is not an option, you can use the insert method (either on the view or on the model):
// model
model.addElementAt(item, model.getSizes();
// alternatively view
combo.insertItemAt(item, combo.getItemCount());
Generally, it's recommended to do model manipulations on the model (vs. on the cover methods on the view) - this way you can implement and test your model handling independent of the view.
Upvotes: 2
Reputation: 324118
the first name in the list automatically gets selected. How to avoid this problem?
Then use:
comboBox.setSelectedIndex(-1);
after the data has been loaded.
Or maybe you could use a Combo Box Prompt.
Upvotes: 2