您将在ComboBox 中显示同时包含name 和id 的项目,并指定如何将这些项目转换为Strings 以显示在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 作为 ComboBox 的项目并使用Map 获取与StringConverter 中的id 关联的字符串。
如果您想在项目的视觉表示方式上增加更多灵活性,您可以使用cellFactory 来创建自定义ListCells(链接的javadoc 中有一个示例)。如果您将它与Integers 0, 1, ..., itemcount-1 中的ComboBox 一起使用,您可能会非常接近android Adapter。但是,在这种情况下,使用 StringConverter 似乎就足够了。