简体   繁体   English

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

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

I'm writing a custom JComboBox and whenever the user types something I want to update the drop down menu of my JComboBox. 我正在编写一个自定义JComboBox,并且每当用户键入某些内容时,我都想更新JComboBox的下拉菜单。 The issue I'm having is that once my DocumentListener sees an update I get an error when I try to add an item to the list. 我遇到的问题是,当我的DocumentListener看到更新时,尝试将项目添加到列表时出现错误。 Here's a basic example of what isn't working: 这是不起作用的基本示例:

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

This isn't actually how my program will work (I'm not just going to add OK each time someone types something), but getting this to work would allow me to implement my custom JComboBox the way it needs to work. 这实际上不是我的程序的工作方式(我不只是要在每次有人键入内容时添加OK),但要使其正常工作,将使我能够按照自己的工作方式实现自定义JComboBox。 Thanks in advance for any help. 在此先感谢您的帮助。

EDIT: The error message I get is: 编辑:我得到的错误信息是:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification 线程“ 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"); 
    }
});

maybe this is what you are looking for 也许这就是您想要的

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