首页 > 解决方案 > 如何使用对象列表中的字符串填充 ComboBox?

问题描述

我有一个Country具有实例变量的对象列表String countryName;。我不知道如何ComboBox用 Country 对象列表填充 。

我尝试通过创建另一个名为

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

并循环它并将每个实例变量添加countryName到一个新列表中:

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

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

如何将 ComboBox 与我的Country对象一起使用,并仅显示国家/地区名称?

@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

标签: javajavafxcombobox

解决方案


这非常简单,当然它是文档的一部分。

首先,您需要创建一个cellFactory负责设置项目文本的ComboBox项目。

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());
    }

};

然后像这样使用它:

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

然后你可以Countries像这样添加你的:

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

祝你好运!


推荐阅读