jComboBox编辑器返回空字符串



我编写了一个自动完成组合框程序,在该程序中,我在文件中搜索用户输入的单词。这个程序运行得很好,但是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 ();
}

问候

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

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

您应该使用

dataTobeSearched=(String)InstantSearchBox.getSelectedItem()
尽管有其名称,但对于可编辑的组合框,此方法只返回输入的文本。

JComboBox只在内部使用编辑器来临时捕获输入。一旦他们输入了内容,编辑器就会被清除,文本就会被转移回组合框模型。

这允许编辑器同时在多个组合框之间共享——它们只需在需要时跳进去,捕获输入,再次跳出来,并在编辑完成时清除。

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

最新更新