Search code examples
javaswingselectionjcombobox

JComboBox selects the first item by iteself


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.


Solution

  • 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.