简体   繁体   English

JComboBox自行选择第一项

[英]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. 我当前面临的问题是,当我写“ H”时,列表中会填充所有以“ H”开头的名称(根据需要),但是列表中的第一个名称会自动被选择。 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. 请注意,根据mysql查询,所有我想要的条目都被填充到组合框中,问题就在于它自己选择了第一个条目。

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 . 或者,您可以使用组合框提示

that's a quirk of the not-editable JComboBox when adding to an empty box: 当添加到一个空盒子时,这是不可编辑的JComboBox的一个怪癖:

  • using addItem(item) will select that item 使用addItem(item)将选择该项目
  • using insertItemAt(item, 0) will not select that item 使用insertItemAt(item, 0)不会选择该项目

That 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): 因此,如果在填充模型后取消选择(如Rob所建议),则可以使用insert方法(在视图或模型上):

// 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. 通常,建议对模型进行模型操作(相对于视图的Cover方法)-这样,您可以独立于视图来实现和测试模型处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM