0

AutoCompleteTextField接受 aList<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;
    }

}

}

4

0 回答 0