Search code examples
javagwtsuggestbox

How to make SuggestBox (GWT) to suggest using only the first word of the suggestion?


My title may be a bit fuzzy but I want to make my suggestbox to suggest words like this when I type letters into the textbox:

Letter typed in suggestbox: A

A lpaca

A pple

A rgon

NOT like this:

Letter typed in suggestbox:A

A lpaca a cute

A pple a nion

A rgon a ttire

is there any way to make the suggest box to behave like this? I just want the first word couple of words that matches the letter, not including the string with multiple words.

I am using GWT in Eclipse by the way.

EDIT: I suck at formatting, the words are

Alpaca

Apple

Argon


Alpaca acute

Apple anion

Argon attire

EDIT AGAIN: I want them to be appear like this:

Entry: Exec

Suggestion:

Execute

Execution

Executor

Entry: Execution t

Suggestion:

Execution time

Execution timer

Execution title

Basically I want it to work like google searches, where the multiple worded suggestions won't appear as long as I haven't typed a second word.


Solution

  • Extending SuggestOracle is the way to go! Please check the code below... Once your implementation is correct, pass a new instance of your oracle to your SuggestBox.

    s.startsWith(userInput) answers the core of your needs. But you can write other conditions of course.

       public class MySuggestOracle extends SuggestOracle {
    
            private List<String> data;
    
            public MySuggestOracle(List<String> data) {
                this.data = data;
            }
    
            @Override
            public void requestSuggestions(final Request request, final Callback callback) {
                String userInput = request.getQuery();
                List<Suggestion> suggestions = new LinkedList<Suggestion>();
                for (final String s : data) {
                    if (s.startsWith(userInput)) {
                        suggestions.add(new Suggestion() {
                            @Override
                            public String getReplacementString() {
                                return s;
                            }
    
                            @Override
                            public String getDisplayString() {
                                return s;
                            }
                        });
                    }
                }
                Response response = new Response(suggestions);
                callback.onSuggestionsReady(request, response);
            }
        }