1

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?
  }
});
Isaac
  • 1,677
  • 3
  • 15
  • 22

2 Answers2

1
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

You need to implement your own MutableComboBoxModel since DefaultComboBoxModel is responsible for the "add item then auto select it" behavior.

Walter Laan
  • 2,956
  • 17
  • 15