I'm trying to use an editable JComboBox
such that upon a user typing into the editor, possible results are displayed in the list part of the combo box.
Unfortunately, I've found that upon using either addItem(item)
or getModel().addItem(item)
, the input typed by the user is overwritten by the first value I added. I've considered storing the editor value, adding items, and then using setSelectedItem()
to fix this, but I wan't to preserve the state of any selected text/ caret position, and believe this should be something more trivial, but can't for the life of me figure it out.
JComboBox box = new JComboBox();
box.setModel(new MutableComboBoxModel());
box.setEditable(true);
box.getEditor().getEditorComponent().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
// Actual results are retrieved from server via HTTP
box.addItem("Demo");
// Here, the editor window the user was typing in is replaced with the value "Demo".. how to fix this?
}
});