Charm AutoCompleteTextField setSelectedItem

时间:2016-11-16 00:35:25

标签: gluon gluon-mobile

AutoCompleteTextField为其完成功能接受List<T>。 虽然可以使用String初始化它,但似乎无法使用类型为T的对象初始化它,因为AutoCompleteTextField.valueProperty是readOnly且没有SelectionModel

public class GluonApplication extends MobileApplication {

@Override
public void init() {
    ObservableList<Person> persons = getPersons();
    Person defaultPerson = persons.get(0);
    FilteredList<Person> personsFiltered = new FilteredList<>(persons);

    AutoCompleteTextField<Person> txtPerson = new AutoCompleteTextField<>();
    txtPerson.setCompleter(s ->
    {
        personsFiltered.setPredicate(person -> person.name.contains(s));
        return personsFiltered;
    });

    TextField txtSelectedPerson = new TextField();
    txtPerson.valueProperty().addListener((obsValue, p, p1) -> txtSelectedPerson.setText(p1.name));

    Button btnSave = new Button("SAVE");
    btnSave.setOnAction(e ->
    {
        Person selectedPerson = txtPerson.getValue(); //if no autocomplete suggestion was selected, valueProperty is empty
        // save selectedPerson
    });

    VBox root = new VBox(txtPerson, txtSelectedPerson, btnSave);
    root.setAlignment(Pos.CENTER);

    addViewFactory(HOME_VIEW, () ->
    {

        View view = new View(root) {
            @Override
            protected void updateAppBar(AppBar appBar) {
                appBar.setTitleText("AutoCompleteTest");
            }
        };

        view.setOnShowing(e -> txtPerson.setText(defaultPerson.name));  // here I would like to set the person object instead
                                                                        // of its string representation
        return view;
    });
}

private ObservableList<Person> getPersons() {
    return FXCollections.observableArrayList(new Person("person1"), new Person("person2"), new Person("person3"));
}

private static class Person {

    private String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

}

}

0 个答案:

没有答案