Samuel Sjöberg's weblog

Skip to navigation

Autocompletion follow up

As pointed out in the comments for the Autocompletion in Swing post, there was a problem when providing default values that had a match returned by the CompletionService.

To reproduce the problem, one had to add the following (in bold) to the provided sample code:

input.setDocument(autoCompleteDocument);

// After setting the document, add a default value
input.setText("Chloe");

The result was an empty text box. If the value instead was Chlo the value in the text box was set to e.

These problems occurred because JTextComponent.setText(String) delegates to Document.insertString where autocompletion happens. The autocompletion code did not handle scenarios when there wasn't any existing text value. The solve the problem, it was necessary to check that some text already existed before applying the completion. In code (changes in bold):

/** {@inheritDoc} */
@Override
public void insertString(int offs, String str, AttributeSet a)
        throws BadLocationException {
    if (str == null || str.length() == 0) {
        return;
    }

    String text = getText(0, offs); // Current text.
    String completion = complete(text + str);
    int length = offs + str.length();
    if (completion != null && text.length() > 0) {
        str = completion.substring(length - 1);
        super.insertString(offs, str, a);
        documentOwner.select(length, getLength());
    } else {
        super.insertString(offs, str, a);
    }
}

I have updated the binary and source files linked in the original post.

Pages linking to this entry

Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.

About this post

Created 19th January 2010 20:48 CET. Filed under Java.

0 Comments
0 Pingbacks