簡體   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