简体   繁体   English

如何在不修改编辑器的情况下在JComboBox上使用addItem()?

[英]How to use addItem() on a JComboBox without modifying the editor?

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. 我正在尝试使用可编辑的JComboBox ,以便在用户输入编辑器时,可能的结果显示在组合框的列表部分中。

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. 不幸的是,我发现使用addItem(item)getModel().addItem(item) ,用户键入的输入将被我添加的第一个值覆盖。 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. 我曾考虑过存储编辑器值,添加项,然后使用setSelectedItem()修复此问题,但我不想保留任何选定文本/插入符号位置的状态,并且我认为这应该比较琐碎,但是可以不能为我的生活弄清楚。

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?
  }
});

您需要实现自己的MutableComboBoxModel,因为DefaultComboBoxModel负责“添加项目然后自动选择它”行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM