In this blog we will work on implementating a Suggest box which can work similarly as Gmail “To” field where it takes a multiple string by using a de-limiter “,” .
You can see the “,” element which divides the suggest items.this cannot be done by the normal gwt suggest box . lets see how we can make a suggest box like above,
From the java docs we can see a suggest box contains a constructor with suggest oracle and a TextboxBase as arguments. We will use this constructor in implementing the above thing .
public class SuggestTextBox extends TextBoxBase {
protected SuggestTextBox(Element elem) {
super(elem);
}
public SuggestTextBox() {
this(Document.get().createTextInputElement(), "gwt-TextBox");
}
public SuggestTextBox(Element elem,String styleName) {
super(elem);
if (styleName != null) {
setStyleName(styleName);
}
}
public String getText() {
String totalString=super.getText();
String newString=totalString;
if(totalString!=null && !totalString.trim().equals("")){
int lastComma=totalString.indexOf(",");
if(lastComma>0){
newString=totalString.trim().substring(lastComma+1);
}
}
return newString;
}//close of getText
public void setText(String text) {
String totalString=super.getText();
if(text!=null && text.equals("")){
super.setText(text);
}else {
if(totalString!=null){
int lastComma=totalString.trim().indexOf(",");
if(lastComma>0){
totalString=totalString.trim().substring(0, lastComma);
}else {
totalString="";
}
if (!totalString.trim().endsWith(",")
&& !totalString.trim().equals("")) {
totalString = totalString + ", ";
}
totalString = totalString + text + ", ";
super.setText(totalString);
}
}//close of if loop
}//Close of Set Text
}
Now in the onModuleLoad() , we will write the code as
SuggestionOracle oracle=new SuggestionOracle();
SuggestBox box=new SuggestBox(oracle,new SuggestTextBox());
box.setWidth("300px");
HorizontalPanel hPanel=new HorizontalPanel();
hPanel.add(new Label("Suggest Box"));
hPanel.add(box);
RootPanel.get().add(hPanel);