问题
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