0

我编写了一个自动完成组合框程序,在该程序中搜索用户在文件中输入的单词。该程序工作正常,但是,在combobox editor其中输入内容时不会返回任何内容。我不知道为什么会这样。这是处理该问题的代码块。

// 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 ();
}

问候

4

3 回答 3

2

不要使用 KeyListener。在生成 keyPressed 事件时,键入的文本尚未添加到文本字段中。

检查文本字段更改的更好方法是将 DocumentListener 添加到文本字段的 Document 中。有关详细信息,请参阅 Swing 教程中有关如何编写文档侦听器的部分。

于 2013-02-04T15:34:52.397 回答
1

你应该使用

dataTobeSearched = (String) InstantSearchBox.getSelectedItem();
尽管它的名字,对于可编辑的组合框,这个方法只返回输入的文本。

编辑器仅由 JComboBox 在内部使用,以在输入时临时捕获输入。一旦他们键入,编辑器就会被清除,文本会被传输回组合框模型。

这允许编辑器一次在多个组合框之间共享 - 他们只是在需要时跳入,捕获输入,再次跳出并在编辑完成时清除。

于 2013-02-04T14:53:26.543 回答
0

使用InstantSearchBox.getSelectedItem()而不是InstantSearchBox.getEditor().getItem().

于 2013-02-04T14:52:44.660 回答