繁体   English   中英

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

[英]How do I update a JComboBox's list from a Document Listener?

我正在编写一个自定义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:尝试在通知中进行更改

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

也许这就是您想要的

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

暂无
暂无

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

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