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

时间:2023-01-28 07:36:03

I'm writing a custom JComboBox and whenever the user types something I want to update the drop down menu of my 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. Here's a basic example of what isn't working:

我正在编写一个自定义的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");
}

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. Thanks in advance for any help.

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

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:尝试在通知中进行变异

2 个解决方案

#1


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

#2


0  

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

#1


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

#2


0  

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