Codename One - Modify AutoCompleteTextField data in runtime

Viewed 41

I have an AutoCompleteTextField and I want to change its options in runtime. The problem is that I don't know how to show changes.

Here's a very simple example of what I've tried:

public void start() {
    if(current != null){
        current.show();
        return;
    }
    Form form = new Form( new FlowLayout() );

    String [] list2 = { "option A", "option B"};
    AutoCompleteTextField textField2 = new AutoCompleteTextField( list2 );
    form.add( textField2 );

    form.show();

    list2 =  new String [2];
    list2 [0] = "X";
    list2 [1] = "D";
    textField2 = new AutoCompleteTextField( list2 );

    form.show();
}

I always displays "option A" and "option B". I already tried for.repaint(), textField2.repaint()...

Any help will be appreciated.

1 Answers

Try this:

final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {

    @Override
    protected boolean filter(String text) {
        if(text.length() == 0) {
            return false;
        }
        String[] l = changeOptions(text);
        if(l == null || l.length == 0) {
            return false;
        }
        options.removeAll();
        for(String s : l) {
            options.addItem(s);
        }
        return true;
    }

};


private String[] changeOptions(String text){
    String[] list2 =  new String [2];
    if(<some_condition_with_text>){
        list2 [0] = "option A";
        list2 [1] = "option B";
        return list2;
    }
    if(<some_other_condition_with_text>){
        list2 [0] = "X";
        list2 [1] = "D";
        return list2;
    }
}

Take a look at https://www.codenameone.com/javadoc/com/codename1/ui/AutoCompleteTextField.html

Related