0

我正在编写一个自定义的 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 中的异常:尝试在通知中变异

4

2 回答 2

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"); 
    }
});
于 2013-04-01T20:04:37.500 回答
0

也许这就是你要找的

jComboBox2.getEditor().getEditorComponent().addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
  //add your handling code here:
}   });
于 2016-12-11T07:07:39.130 回答