【问题标题】:JavaFX ComboBox - How to get different Prompt Text and Selected Item Text?JavaFX ComboBox - 如何获得不同的提示文本和选定项目文本?
【发布时间】:2016-10-27 01:28:27
【问题描述】:

我搜索了一下,但找不到答案。组合框是可编辑的。如何在组合框提示文本和下面的对象列表中显示不同的文本?在列表中我希望使用 Object 的 toString 方法,但是当我选择它时,我希望在提示文本中只显示所选 Object 的一个属性。

我该怎么做?是否可以在提示文本字段和下面的列表中以不同的方式显示对象的值?

使用的一个例子是歌曲。假设我按标题搜索歌曲,然后它会在下面显示标题、作曲家和乐器的歌曲。当我选择歌曲时,我只想在提示文本中显示标题(因为我在其他地方显示了作曲家和乐器信息)。

【问题讨论】:

  • 是否要使用可编辑 ComboBox 的文本字段来过滤下拉菜单中显示的结果?
  • 请注意,提示文本是显示的文本,如果没有选择任何项目,因此独立于项目的任何toString 方法。这很可能类似于 Please select an item 而不是 toString 项目的结果...在我下面的答案中将其解释为“文本字段中显示的文本”。如果这是不正确的解释,请在评论中告诉我...

标签: java javafx combobox


【解决方案1】:

使用converter(使用短版本进行转换)和自定义cellFactory 创建显示扩展版本的单元格:

static class Item {
    private final String full, part;

    public Item(String full, String part) {
        this.full = full;
        this.part = part;
    }

    public String getFull() {
        return full;
    }

    public String getPart() {
        return part;
    }

}

@Override
public void start(Stage primaryStage) {
    ComboBox<Item> comboBox = new ComboBox<>(FXCollections.observableArrayList(
            new Item("AB", "A"),
            new Item("CD", "C")
    ));

    comboBox.setEditable(true);

    // use short text in textfield
    comboBox.setConverter(new StringConverter<Item>(){

        @Override
        public String toString(Item object) {
            return object == null ? null : object.getPart();
        }

        @Override
        public Item fromString(String string) {
            return comboBox.getItems().stream().filter(i -> i.getPart().equals(string)).findAny().orElse(null);
        }

    });

    comboBox.setCellFactory(lv -> new ListCell<Item>() {

        @Override
        protected void updateItem(Item item, boolean empty) {
            super.updateItem(item, empty);

            // use full text in list cell (list popup)
            setText(item == null ? null : item.getFull());
        }

    });

    Scene scene = new Scene(comboBox);

    primaryStage.setScene(scene);
    primaryStage.show();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    相关资源
    最近更新 更多