1

我已经搜索了谷歌,但没有找到任何有用的信息。
我正在使用Adapter for combobox 来选择name并获取它的id。(不是位置索引,id来自数据库)在 Android 中。但我不知道如何在 JavaFx 中使用它?

我在来自数据库idname的列表中尝试了 JavaFx POJO。 我添加到ObservableList 和Combobox。 当ComboBox选择获取其位置索引并使用此索引并从列表中获取真实ID。
setItems(list.getName())
list.getID(index)

这是最好/正确的方法吗?或者是否有 Java FX 的 Android 适配器替代品?

4

1 回答 1

1

您将在 中显示同时包含nameid的项目,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来创建自定义ListCells(链接的 javadoc 中有一个示例)。如果您将它与 a ComboBoxof Integers一起使用,0, 1, ..., itemcount-1您可能会非常接近 android Adapter。但是StringConverter,在这种情况下使用 a 似乎就足够了。

于 2015-11-12T11:53:22.093 回答