如何从文档侦听器更新JComboBox的列表?

时间:2013-04-01 19:27:38

标签: java swing jcombobox documentlistener

我正在编写一个自定义的JComboBox,每当用户键入内容时,我想更新我的JComboBox的下拉菜单。我遇到的问题是,一旦我的DocumentListener看到更新,当我尝试将项目添加到列表时,我会收到错误。 这是一个不起作用的基本例子:

public class InputField extends JComboBox<String> implements DocumentListener{

//when something is typed, gets suggestions and adds them to the popup
@Override
 public void insertUpdate(DocumentEvent ev) {
    try{
        giveSuggestions(ev);
    }
    catch(StringIndexOutOfBoundsException e){

    }
}
private void giveSuggestions(DocumentEvent ev){
    this.addItem("ok");
}

这实际上并不是我的程序如何工作(我不只是每次有人输入时都会添加OK),但是让它工作将允许我按照它需要的方式实现我的自定义JComboBox。提前感谢您的帮助。

编辑:我得到的错误信息是:

  

线程“AWT-EventQueue-0”中的异常java.lang.IllegalStateException:尝试在通知中进行变异

2 个答案:

答案 0 :(得分:3)

SwingUtilities.invokeLater(new Runnable()
{
    public void run()
    {
        this.addItem("ok");
        // I can never remember the correct way to invoke a class method            
        // from witin and anonymous inner class
        //InputField.addItem("ok"); 
    }
});

答案 1 :(得分:0)

也许这就是你要找的东西

jComboBox2.getEditor().getEditorComponent().addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
  //add your handling code here:
}   });
相关问题