Search code examples
javajavafxcombobox

How to populate ComboBox with Strings from a list of objects?


I have a list of Country objects that have the instance variable String countryName;. I can't figure out how to populate the ComboBox with a list of Country objects.

I tried doing it using a workaround by creating another list called

ObservableList<String> listCountriesString = FXCollections.observableArrayList();

and looping over it and adding every instance variable countryName to a new list:

private ObservableList<Country> listCountries = FXCollections.observableArrayList();

for (Country country : listCountries) {
    listCountriesString.add(country.getCountryName());
}

How can I use a ComboBox with my Country object, and displaying the country names only?

@FXML
ComboBox<Country> comboBoxCountry;
public class Country {
    private int countryId;
    private String countryName;
    private String createDate;
    private String lastUpdate;

    public Country(int countryId, String countryName, String createDate, String lastUpdate) {
        this.countryId = countryId;
        this.countryName = countryName;
        this.createDate = createDate;
        this.lastUpdate = lastUpdate;
    }

    ... getters and setters

Solution

  • It's pretty straightforward and it is part of the documentation of course.

    First you would need to create a cellFactory that takes care of setting the text of your ComboBox items.

    Callback<ListView<Country>, ListCell<Country>> cellFactory = lv -> new ListCell<Country>() {
    
        @Override
        protected void updateItem(Country item, boolean empty) {
            super.updateItem(item, empty);
            setText(empty ? "" : item.getCountryName());
        }
    
    };
    

    And then use it like this:

    comboBoxCountry.setButtonCell(cellFactory.call(null));
    comboBoxCountry.setCellFactory(cellFactory);
    

    Then you could add your Countries like this:

    comboBoxCountry.getItems().add(new Country("Germany"...));
    

    Good luck!