我正在编写一个自定义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: Attempt to mutate in notification
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:
} });