I am having an editable jCombobox , and it will search for selected users if you enter something inside and click enter, this is my code
jComboBoxReceiver.getEditor().getEditorComponent().addKeyListener(new java.awt.event.KeyAdap开发者_开发百科ter() {
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);
}
}
});
And then, for example , if you type f, it should return Fred and Fried Chicken, but after it found the result, it will go search again for Fred which is the first item by itself... can anyone tell me why ?
Instead of replacing the combo box model, try just updating the model.
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());
}
}
}
};
When you set the model, you are resetting the JComboBox's view of its world. In particular, when the model is replaced the selection is set to the model's selected item. This is by default the first item. In your case "Fred". This replaces whatever the user has typed in the combobox editor.
精彩评论