Question

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:

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.

EDIT: The error message I get is:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification

Was it helpful?

Solution

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

OTHER TIPS

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:
}   });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top