【问题标题】:Android adapter alternative in Java FXJava FX 中的 Android 适配器替代方案
【发布时间】:2016-02-13 12:21:22
【问题描述】:

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

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

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

【问题讨论】:

    标签: java android javafx combobox observablelist


    【解决方案1】:

    您将在ComboBox 中显示同时包含nameid 的项目,并指定如何将这些项目转换为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 似乎就足够了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2012-07-26
      • 2013-03-10
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多