我有一个可编辑的jCombobox,如果你在里面输入内容它会搜索选定的用户,然后点击回车,这是我的代码
jComboBoxReceiver.getEditor().getEditorComponent().addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
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();
}
DefaultComboBoxModel modelList = new DefaultComboBoxModel(userList);
jComboBoxReceiver.setModel(modelList);
}
}
});
然后,例如,如果你输入f,它应该返回Fred和Fried Chicken,但是在找到结果之后,它将再次搜索Fred,这是第一个项目......有人能告诉我为什么?
答案 0 :(得分:0)
不要替换组合框模型,只需更新模型即可。
jComboBoxReceiver.getEditor().getEditorComponent().addKeyListener(new
java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));
usrList = sr.searchUser();
DefaultComboBoxModel model = jComboBoxReceiver.getModel();
model.removeAllElements();
for(int i=0;i<usrList.size();i++){
model.addElement(usrList.get(i).getUserName());
}
}
}
};
设置模型时,您将重置JComboBox的世界视图。特别是,当替换模型时,选择将设置为模型的选定项目。默认情况下,这是第一项。在你的情况下“弗雷德”。这取代了用户在组合框编辑器中输入的内容。