Codename one - autocompletetextfield getitem被选中

时间:2017-04-27 12:54:57

标签: codenameone

我有两个问题:

1)首先,我想在AutoCompleteTextFieldDefaultListModel完全添加地图,然后我想在autocompletetextField

中添加listmodel

2)当我在AutoCompleteTextField

中选择元素时,如何获取文本
    Form hi = new Form("Auto Complete", new BoxLayout(BoxLayout.Y_AXIS));
        AutoCompleteTextField ac = new AutoCompleteTextField("Short", "Shock", "Sholder", "Shrek0", "3asna", "niazra");
    ac.setMinimumElementsShownInPopup(5);
    //final DefaultListModel<Map<String,Object>> options = new DefaultListModel<>();
    final DefaultListModel<String> options = new DefaultListModel<>();

    AutoCompleteTextField an = new AutoCompleteTextField(options);
    hi.add(an);
    ac.addListListener(a -> {
        List<Object> ls = new List<>();
        System.out.println("i want to display the text selected");

    });
    hi.add(ac);
    hi.show();

1 个答案:

答案 0 :(得分:2)

当您在AutoCompleteTextField的建议框中选择一个项目时,此项目的文本将被复制到AutoCompleteText字段的TextField部分,但这只发生在ListEvent之后。

为了产生这种行为,首选使用DefaultListModel上的Selection Listener:

    Form hi = new Form("ACTF", new BoxLayout(BoxLayout.Y_AXIS));

    DefaultListModel<String> defList = new DefaultListModel<>("Red", "Green", "Blue", "Orange");
    AutoCompleteTextField tf1 = new AutoCompleteTextField(defList);

    defList.addSelectionListener((oldid, newid)-> Log.p(defList.getItemAt(newid)));

    hi.add(tf1);
    hi.show();

我不知道为什么,在显示表单后会出现两次,但之后效果非常好。

修改:如果要在屏幕上显示文字,则必须使用以下内容:

    Form hi = new Form("ACTF", new BoxLayout(BoxLayout.Y_AXIS));

    Label text = new Label("Selected text");

    DefaultListModel<String> defList = new DefaultListModel<>("Red", "Green", "Blue", "Orange");
    AutoCompleteTextField tf1 = new AutoCompleteTextField(defList);

    defList.addSelectionListener((oldid, newid)-> {
        text.setText(defList.getItemAt(newid));
        hi.revalidate();
    });
    hi.add(text);
    hi.add(tf1);
    hi.show();

编辑2 :链接地图示例:

    Form hi = new Form("ACTF", new BoxLayout(BoxLayout.Y_AXIS));

    Map testMap = new HashMap<String, String>();
    testMap.put("Red", "Roses are red");
    testMap.put("Green", "Grass is green");
    testMap.put("Blue", "Sky is blue");
    testMap.put("Orange", "Apricots are orange");

    Label text = new Label("Selected text");



    DefaultListModel<String> defList = new DefaultListModel<>(testMap.keySet());
    AutoCompleteTextField tf1 = new AutoCompleteTextField(defList);

    defList.addSelectionListener((oldid, newid)-> {
        text.setText((String) testMap.get(defList.getItemAt(newid)));
        hi.revalidate();
    });
    hi.add(text);
    hi.add(tf1);
    hi.show();