Java FX中的Android适配器替代

时间:2015-11-12 08:20:14

标签: java android javafx combobox observablelist

我已经访问了谷歌,但没有找到任何有用的信息 我使用Adapter组合框选择名称并获取 ID 。 (不是位置索引, id 来自数据库)在Android中。但我不知道如何在JavaFx中使用它?

我在列表中尝试了JavaFx POJO,该列表来自数据库 id 名称
我向Combobox添加了ObservableListsetItems(list.getName()) 当Combobox选择获取它的位置索引并使用此索引并从列表中获取真实ID。 list.getID(index)

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

1 个答案:

答案 0 :(得分:1)

You would show items that contain both name and id in the ComboBox and specify how the items are converted to Strings that are shown in the 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;
    }

}

Of course you could also use a different kind of items, if that's more convenient for you. E.g. Integer(= indices in list) could be used and the StringConverter could be used to convert the index to a name from the list (and id) or you could use the ids as items of the ComboBox and use a Map to get the strings associated with the ids in the StringConverter.

If you want to add more flexibility in how your items are represented visually, you could use a cellFactory instead to create custom ListCells (there is an example in the javadoc linked). If you use this together with a ComboBox of Integers 0, 1, ..., itemcount-1 you could get pretty close to a android Adapter. However using a StringConverter seems to be sufficient in this case.