How do I display all country list in ComboBox? [JavaFX]

左心房为你撑大大i 提交于 2019-12-12 05:13:56

问题


public void start(final Stage frame) throws Exception {
    String[] locales = Locale.getISOCountries();
    for (String countrylist : locales) {
        Locale obj = new Locale("", countrylist);
        String[] city = {obj.getDisplayCountry()};
        for (int x = 0; x < city.length; x++) {
            cities = FXCollections.observableArrayList(obj.getDisplayCountry());
            country = new ComboBox<String>(cities);
        }
    }
}

I want to display the country list using Locale class. However I only manage to display one country in the Combobox when I run the code. I am not sure whether I got the loop wrong or what.


回答1:


Use This code

  public void start(Stage primaryStage) throws Exception {

                ObservableList<String> cities = FXCollections.observableArrayList();
                ComboBox<String> country = new ComboBox<String>(cities);

                String[] locales1 = Locale.getISOCountries();
                for (String countrylist : locales1) {
                    Locale obj = new Locale("", countrylist);
                    String[] city = { obj.getDisplayCountry() };
                    for (int x = 0; x < city.length; x++) {
                        cities.add(obj.getDisplayCountry());
                    }
                }
                country.setItems(cities);
 }



回答2:


you are creating a new combo box every loop, try creating it outside the loops and only fill it inside?

Hope that helps.

Greetings,

Gian-Marco




回答3:


You are creating new ComboBox in every iteration, that is why you always get ComboBox with single country(last country in list). You can use Stream to get all countries.

ObservableList<String> countries = Stream.of(Locale.getISOCountries())
        .map(locales -> new Locale("", locales))
        .map(Locale::getDisplayCountry)
        .collect(Collectors.toCollection(FXCollections::observableArrayList));

ComboBox<String> cb = new ComboBox<>(countries);



回答4:


here you get the list

    ComboBox<String> country = new ComboBox<>();
    String[] locales = Locale.getISOCountries();
    for (String countrylist : locales) {
        Locale obj = new Locale("", countrylist);
        String[] city = {obj.getDisplayCountry()};
        country.setItems(FXCollections.observableArrayList(locales));
    }


来源:https://stackoverflow.com/questions/43674408/how-do-i-display-all-country-list-in-combobox-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!