您將顯示包含在ComboBox
都name
和id
並指定項目如何轉換爲那些在ComboBox
所示String
的項目進行。
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來代替創建自定義ListCell
(在鏈接的javadoc中有一個示例)。如果你使用ComboBox
的Integer
s 0, 1, ..., itemcount-1
,你可能會非常接近android Adapter
。然而在這種情況下使用StringConverter
似乎就足夠了。