【问题标题】:Get ID out of combobox (java)从组合框中获取 ID (java)
【发布时间】:2018-11-01 12:31:14
【问题描述】:

我有一个带有变量名称和 ID 的模型。 我有一个组合框,我在这个组合框中添加了模型的名称。 通过这样做:

ObservableList<String> personList = FXCollections.observableArrayList();
personList.add(model.getName);
ComboBox box = new ComboBox(personList);

这可行,但现在当用户选择名称时,我想检索 ID。我怎么能这样做?我无法创建一个遍历“模型列表”并查找名称的 for 循环,因为名称不是唯一的。

【问题讨论】:

    标签: java javafx combobox


    【解决方案1】:

    ComboBox的元素类型更改为同时包含id和name的类型。 (顺便说一句,使用 raw 类型是不好的做法。)使用自定义 cellFactory 正确显示项目。这允许您通过ComboBoxvalue 属性检索包含您需要的所有信息的对象:

    @Override
    public void start(Stage primaryStage) {
        class Item {
            final int id;
            final String text;
    
            public Item(int id, String text) {
                this.id = id;
                this.text = text;
            }
    
        }
    
        ComboBox<Item> comboBox = new ComboBox<>();
        for (int i = 0; i < 26*2; i++) {
            comboBox.getItems().add(new Item(i, Character.toString((char) i % ('Z' - 'A' + 1) + 'A')));
        }
    
        class ItemCell extends ListCell<Item> {
    
            @Override
            protected void updateItem(Item item, boolean empty) {
                super.updateItem(item, empty);
    
                setText(item == null ? "" : item.text);
            }
    
        }
    
        comboBox.setCellFactory(lv -> new ItemCell());
        comboBox.setButtonCell(new ItemCell());
    
        comboBox.valueProperty().addListener((o, oldValue, newValue) -> {
            System.out.format("%02d: %s\n", newValue.id, newValue.text);
        });
    
        StackPane root = new StackPane(comboBox);
    
        Scene scene = new Scene(root, 300, 300);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-19
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多