【问题标题】:How to populate ComboBox with Strings from a list of objects? [duplicate]如何使用对象列表中的字符串填充 ComboBox? [复制]
【发布时间】:2021-10-22 15:23:33
【问题描述】:

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

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

的列表来使用解决方法

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

【问题讨论】:

标签: java javafx combobox


【解决方案1】:

它非常简单,当然它是documentation 的一部分。

首先,您需要创建一个 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"...));

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2013-12-19
    • 2012-01-26
    • 1970-01-01
    相关资源
    最近更新 更多