6.2. AutoSuggest
AutoSuggest
accepts user input and displays matching list of Symbols
for selection. It uses GWT SuggestBox
to display suggestions those
matches input.
Default SuggestOracle
of SuggestBox
is MultiWordSuggestOracle
which displays sorted drop down list of matches. List of names comes
from SymbolDatabase.getSymbolNames()
, which returns names of four
symbols, and method MultiWordSuggestOracle.setSymbolNames()
adds list
to the oracle.
in.fins.client.widget/AutoSuggest.java
private void setSymbolNames() {
List<String> list = SymbolDatabase.getSymbolNames();
((MultiWordSuggestOracle) suggestBox.getSuggestOracle()).addAll(list);
}
In Part 2 of the book, RPS calls to the server replaces SymbolDatabase
calls.
To handle the text, SuggestBox
provides two handlers
ValueChangeHandler
and SelectionHandler
. We may either of them to
handle selection, but ValueChangeHandler
may not work seamlessly
across browsers while SelectionHandler
works seamlessly in all
browsers. @UiHandler annotated handlSelection()
method handles
SelectionEvent. On selection, name is cleared from SuggestBox so that it
is ready for the next input. We are going use the selected name in the
next section, and for the time being handler just logs log tab.
in.fins.client.widget/AutoSuggest.java
@UiHandler("suggestBox")
public void handleSelection(SelectionEvent<SuggestOracle.Suggestion> s) {
log.fine("Selection : " + suggestBox.getText());
suggestBox.setText("");
}
It is also possible to code the Handler as anonymous inner class as shown in following snippet but @UiHandler method is clear and easy to read.
suggestBox.addSelectionHandler(new
SelectionHandler<SuggestOracle.Suggestion>() {
@Override
public void onSelection(SelectionEvent<Suggestion> event) {
log.fine("Selection : " + suggestBox.getText());
suggestBox.setText("");
}
});
On page load, we have to focus the AutoSuggest
for user input. SuggestionBox.setFocus()
call will not set focus as widgets are still
being constructed and we have to call setFocus()
method once the page
loads the entire widget tree into browser. To do this, defer its
execution by delegating the command to a Scheduler
which executes
setFocus()
method once page loads the widgets tree.
in.fins.client.widget/AutoSuggest.java
public void requestFocus() {
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
public void execute() {
suggestBox.setFocus(true);
}
});
}
Once UiBinder creates and binds the UI, constructor calls
requestFocus()
method.
in.fins.client.content/Snapshot.java
public Snapshot() {
initWidget(binder.createAndBindUi(this));
autoSuggest.requestFocus();
Note
SymbolDatabase
returns four symbol names A Sys, B Max, C World and D
Dummy, and use A, B, C or D in AutoSuggest as input to get drop down
list.
AutoSuggest
is ready to accept the user input, but it just logs the
Symbol name, and in the next section we design a widget to display the
symbol name.