Fork us on GitHub

Dynamic AutoComplete

Using the auto-complete text field with a webservice
Dynamic AutoComplete

Dynamic AutoComplete

With the fix for issue #1694 we can now have a moderately simple method of creating an AutoCompleteTextField that works with a webservice. This has been requested quite often and was quite frustrating to implement in the past it is now relatively simple with just a few lines of code.

Check out the live demo using the JavaScript port on the right side here

You can see the full working sample of this project in this github repository notice that you will need to fill in a google web API key for the webservice to work as explained here.

The sample works relatively simply, instead of passing a fixed list of elements we pass a model to the auto complete and then just modify the model. The auto complete updates itself based on the modification to the model which is completely asynchronous.

The main thing we need to do is override the filter method and mutate the model there.

Check out the main code of this app below:

Form hi = new Form("AutoComplete", new BoxLayout(BoxLayout.Y_AXIS));
if(apiKey == null) {
    hi.add(new SpanLabel("This demo requires a valid google API key to be set in the constant apiKey, "
            + "you can get this key for the webservice (not the native key) by following the instructions here: "
            + ""));
    hi.getToolbar().addCommandToRightBar("Get Key", null, e -> Display.getInstance().execute(""));;
 final DefaultListModel<String> options = new DefaultListModel<>();
 AutoCompleteTextField ac = new AutoCompleteTextField(options) {
     protected boolean filter(String text) {
         if(text.length() == 0) {
             return false;
         String[] l = searchLocations(text);
         if(l == null || l.length == 0) {
             return false;

         for(String s : l) {
         return true;

Notice that it relies on a call to the Google webservice as such:

String[] searchLocations(String text) {
    try {
        if(text.length() > 0) {
            ConnectionRequest r = new ConnectionRequest();
            r.addArgument("key", apiKey);
            r.addArgument("input", text);
            Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
            String[] res = Result.fromContent(result).getAsStringArray("//description");
            return res;
    } catch(Exception err) {
    return null;
Share this Post:

Posted by Shai Almog

Shai is the co-founder of Codename One. He's been a professional programmer for over 25 years. During that time he has worked with dozens of companies including Sun Microsystems.
For more follow Shai on Twitter & github.