您将在 中显示同时包含name
和id
的项目,ComboBox
并指定如何将项目转换为String
在 中显示的 s ComboBox
。
ComboBox<Item> comboBox = new ComboBox<>();
comboBox.setItems(FXCollections.observableArrayList(new Item("foo", "17"), new Item("bar", "9")));
comboBox.setConverter(new StringConverter<Item>() {
@Override
public Item fromString(String string) {
// converts string the item, if comboBox is editable
return comboBox.getItems().stream().filter((item) -> Objects.equals(string, item.getName())).findFirst().orElse(null);
}
@Override
public String toString(Item object) {
// convert items to string shown in the comboBox
return object == null ? null : object.getName();
}
});
// Add listener that prints id of selected items to System.out
comboBox.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Item> observable, Item oldValue, Item newValue) -> {
System.out.println(newValue == null ? "no item selected" : "id=" + newValue.getId());
});
class Item {
private final String name;
private final String id;
public String getName() {
return name;
}
public String getId() {
return id;
}
public Item(String name, String id) {
this.name = name;
this.id = id;
}
}
当然,您也可以使用其他种类的物品,如果这对您来说更方便的话。例如Integer
(= 列表中的索引)可以StringConverter
用于将索引转换为列表(和 id)中的名称,或者您可以将 id 用作 the 的项目ComboBox
并使用 aMap
来获取与 id 关联的字符串在StringConverter
.
如果您想在项目的视觉表示方式上增加更多灵活性,您可以使用cellFactory来创建自定义ListCell
s(链接的 javadoc 中有一个示例)。如果您将它与 a ComboBox
of Integer
s一起使用,0, 1, ..., itemcount-1
您可能会非常接近 android Adapter
。但是StringConverter
,在这种情况下使用 a 似乎就足够了。