文本字段中的自动建议,数据来自 Google API

Auto suggestion in text field with data from Google API

我想制作一个带有建议的自动完成文本字段,其中数据来自 Google API - 在按下每个新键后更新。 现在,我有一个方法可以下载 5 个建议并在按下另一个键时更新它们。

我已经尝试 AutoCompleteTextField 来自 Gluon,但效果不佳。

public class Controller {
    Weather weather = new Weather();
    GooglePlaces googlePlaces = new GooglePlaces();

    @FXML
    AutoCompleteTextField<String> autoCompleteTextField = new AutoCompleteTextField<>();

    @FXML
    public void setAutoComplete() throws IOException {
        ArrayList<String[]> places = googlePlaces.predictPlaces("New yo");

        autoCompleteTextField.setCompleter(s -> {
            ArrayList<String> autoplaces = new ArrayList<>();
            for (int i = 0; i < places.size(); i++) {
                autoplaces.add(places.get(i)[0]);
            }
            System.out.println("test");
            return autoplaces;
        });
    }
}

在这里,我尝试在 "New yo" 阶段添加 5 个建议,但没有在每个新密钥之后更新,但它也没有用,因为它没有显示任何内容。 "test" 未在控制台中打印。

在我看来,您需要在名为 initialize():

的方法中调用 setCompleter()
public class Controller {

    @FXML
    public void initialize() {
        autoCompleteTextField.setCompleter(input -> {
            List<String[]> places = googlePlaces.predictPlaces(input);
            // ...
        });
    }
}

另见: