James Aflred
James Aflred

Reputation: 97

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. 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

Upvotes: 0

Views: 261

Answers (3)

camickr
camickr

Reputation: 324207

Don't use a KeyListener. The text typed has not beeen added to the text field when at the time a keyPressed event is generated.

The better way to check for changes to the text field is to add a DocumentListener to the Document of the text field. See the section from the Swing tutorial on How to Write a Document Listener for more information.

Upvotes: 2

David Lavender
David Lavender

Reputation: 8331

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. 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.

Upvotes: 1

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13900

Use InstantSearchBox.getSelectedItem() instead of InstantSearchBox.getEditor().getItem().

Upvotes: 0

Related Questions