简体   繁体   English

jComboBox编辑器返回空字符串

[英]jComboBox editor returns empty String

I wrote a autocomplete combobox program in which I search for the words entered by the user inside a file. 我编写了一个自动完成组合框程序,在其中搜索用户在文件内输入的单词。 The program works fine, however, the combobox editor doesn't return anything when something is typed in it. 该程序运行良好,但是,在其中键入内容时, combobox editor不返回任何内容。 I don't know why is that.. Here is the chunk of code that deals with the problem. 我不知道为什么。这是处理该问题的代码块。

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

Regards 问候

Don't use a KeyListener. 不要使用KeyListener。 The text typed has not beeen added to the text field when at the time a keyPressed event is generated. 在生成keyPressed事件时,尚未将键入的文本添加到文本字段中。

The better way to check for changes to the text field is to add a DocumentListener to the Document of the text field. 检查文本字段更改的更好方法是将DocumentListener添加到文本字段的Document中。 See the section from the Swing tutorial on How to Write a Document Listener for more information. 有关更多信息,请参见Swing教程中有关如何编写文档侦听器的部分。

You should use 你应该用

dataTobeSearched = (String) InstantSearchBox.getSelectedItem();
Despite its name, for editable comboboxes, this method just returns what text is entered. 尽管名称如此,但对于可编辑的组合框,此方法仅返回输入的文本。

The editor is only used internally by JComboBox to temporarily capture the input as they are typing. JComboBox仅在内部使用该编辑器来在输入时临时捕获输入。 Once they have typed, the editor is cleared down and the text transferred back to the combobox model. 键入后,将清除编辑器,并将文本传输回组合框模型。

This allows editors to be shared amongst multiple comboboxes all at once - they just jump in when they are needed, capture input, jump back out again and clear down when editing is finished. 这样一来,编辑人员就可以一次在多个组合框中共享-它们仅在需要时跳入,捕获输入,再次跳出并在完成编辑后清除。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM