java - 如何使用对象列表中的字符串填充 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
解决方案
这非常简单,当然它是文档的一部分。
首先,您需要创建一个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"...));
祝你好运!
推荐阅读
- android - Android Progaurd 规则包名称正则表达式
- python-3.x - 使用 re.sub 替换字符串中的子字符串?
- c++ - 在哪里可以找到 gtk.lib 文件?
- c# - (C# VB) 我可以动态更改类中所有变量的值吗?
- java - android项目的必要文件未显示在github上
- postgresql - 基于先前值的 postgresql 条件滞后
- docker - 使用 istio 创建 bookinfo 示例时 ReplicaFailure 设置为 FailedCreate
- angular - 如何在角度材料中将我们自己的功能分配给 MatDialog
- php - 将 mysql 转换为 mysqli 谷歌图表的程序方式
- c# - EF Core 5:不要为属性创建索引(使用外键)