2013-02-04 116 views
0

我寫了一個自動完成組合框程序,其中我搜索用戶在文件中輸入的單詞。該程序工作正常,但是,combobox editor不會返回任何東西時,鍵入內容。我不知道這是爲什麼..這是處理問題的代碼塊。jComboBox編輯器返回空字符串

// in GUI class constructor 
    InstantSearchBox = new JComboBox(); 
    InstantSearchBox.setEditable(true); 

    /*****/ 
    KeyHandler handle = new KeyHandler(); 

    InstantSearchBox.getEditor().getEditorComponent().addKeyListener(handle); 


// Keylistener class (KeyPressed method) 
try 
{ 
    dataTobeSearched = InstantSearchBox.getEditor().getItem().toString(); 

    // the string variable is empty for some reason 
    System.out.println ("Data to be searched " + dataTobeSearched); 
} 
catch (NullPointerException e) 
{ 
    e.printStackTrace(); 
} 

問候

+1

我會懷疑這種方式可能會提出一些建議......,爲了更好的幫助,儘快發佈一個[SSCCE](http://sscce.org/),短的可運行的,可編譯的,只是關於'JFrame ''JComboBox'和硬編碼值'Items' – mKorbel

+0

這裏有兩個答案,不是,從來沒有,這種方式不可能在'Editor'中捕獲'non_finalized KeyEvents' vs在Swing – mKorbel

回答

2

請勿使用KeyListener。在生成keyPressed事件時,鍵入的文本還沒有添加到文本字段中。

檢查文本字段更改的更好方法是將DocumentListener添加到文本字段的Document中。有關更多信息,請參閱How to Write a Document Listener上的Swing教程部分。

0

使用InstantSearchBox.getSelectedItem()代替InstantSearchBox.getEditor().getItem()

1

您應該使用

dataTobeSearched = (String) InstantSearchBox.getSelectedItem();
儘管它的名稱是可編輯組合框,但此方法僅返回輸入的文本。

編輯器僅在JComboBox內部用於在輸入時臨時捕獲輸入。一旦鍵入完畢,編輯器就會被清除,文本將被傳回到組合框模型。

這允許編輯器一次性在多個組合框之間共享 - 它們只在需要時跳入,捕獲輸入,再次跳出並在編輯完成時清除。

+0

中爲'Autocompleted funcionalities'提供'文檔'我很懷疑你是否誤解了我,或者我無法理解你的觀點。實際上,組合框的工作方式類似於Google搜索框,用戶在其中鍵入內容,並根據輸入內容是否完整,即時搜索在彈出框中提供建議。我試圖實現 –

+0

啊是的。你已經發布了更多的代碼。 –