0

我正在尝试搜索用户名并将值返回到 jComboBox,这是代码

public void actionPerformed(java.awt.event.ActionEvent e) {
    sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));    
    usrList = sr.searchUser();
    String[] userList = new String[usrList.size()] ;
    for(int i=0;i<usrList.size();i++){
        userList[i]= usrList.get(i).getUserName();
    }
    model = new DefaultComboBoxModel(userList);
    jComboBoxReceiver.setModel(model);
}

在你点击到其他地方或点击回车后,它会进行搜索,但是,它会再次搜索第一个项目,这非常令人困惑......然后我尝试使用 key Pressed

if(e.getKeyCode()==13){
    sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));    
    usrList = sr.searchUser();
    String[] userList = new String[usrList.size()] ;
    for(int i=0;i<usrList.size();i++){
        userList[i]= usrList.get(i).getUserName();
    }
    model = new DefaultComboBoxModel(userList);
    jComboBoxReceiver.setModel(model);
}

而这个完全没有反应。

4

3 回答 3

2

您需要在编辑器而不是组合框本身上设置侦听器。在这里查看答案:

检测用户何时在Java中按下回车

于 2011-02-01T16:10:58.153 回答
1

IMO,真正让您的用户感到困惑的是,一旦他们选择其中一个选项,组合框的内容和选择就会更改。

无论如何,如果您真的想这样做,那么您应该在更改其内容之前删除动作侦听器(或停用它),并在之后重新添加它(或重新激活它):

public void actionPerformed(java.awt.event.ActionEvent e) {
    sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));    
    usrList = sr.searchUser();
    String[] userList = new String[usrList.size()] ;
    for(int i=0;i<usrList.size();i++){
        userList[i]= usrList.get(i).getUserName();
    }
    model = new DefaultComboBoxModel(userList);
    jComboBoxReceiver.removeActionListener(this);
    jComboBoxReceiver.setModel(model);
    jComboBoxReceiver.addActionListener(this);
}
于 2011-02-01T15:45:48.157 回答
1

哇,你每次都在重建一个 ComboBoxModel 吗?是不是有点贵?您知道有一个MutableComboBoxModel, 也由它实现,DefaultComboBoxModel它允许您在组合框中添加/删除元素,而无需每次都重建其模型?

关于你的问题,我不明白这个说法

但是,如果我这样做,它确实可以正确执行,但是,它将再次搜索第一项

你的意思是你的 JComboBox 开始闪烁,内容每次都被修改?

如果是这样,可能是因为您ActionListener链接到JComboBox,内容不断变化。

无论如何,我建议你添加一些日志,比如

sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));    
DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBoxReceiver.getModel();
model.remvoeAllElements();
usrList = sr.searchUser();
String[] userList = new String[usrList.size()] ;
for(int i=0;i<usrList.size();i++){
    String username = usrList.get(i).getUserName();
    System.out.println(username); // feel free to instead use one loger
    model.addElement(username);
}

此外,我倾向于向您建议另一种方法,其中组合框模型不包含简单的字符串,而是包含用户对象,ListCellRenderer仅显示用户名。

于 2011-02-01T15:50:18.850 回答