【问题标题】:JavaFX ComboBox items are getting cleared on selection [duplicate]JavaFX ComboBox 项目在选择时被清除[重复]
【发布时间】:2017-10-10 04:26:09
【问题描述】:

我有一个奇怪的问题。我在 JavaFX 中使用 ComboBox,其中每个项目都是 HBox,并且是图像和标签的组合。

list.forEach(continent -> {
    Image image = new Image(getClass().getResourceAsStream(continent + ".png"));
    ImageView imageView = new ImageView(image);
    imageView.setFitHeight(25);
    imageView.setFitWidth(25);
    imageCombo.getItems().add(new HBox(imageView, new Label(continent)));
 });

list 是一个字符串数组列表。 imageCombo 只是 ComboBox<HBox> 以下是我启动应用程序时的结果。

到目前为止没有问题。但是,当我选择其中一项时,问题就来了。当我这样做时,它会被选中,但是当我再次展开组合框列表时,先前选择的项目变为空白,如果我选择该项目,那也将不可见。我尝试使用 Cell Factory,似乎对我没有多大帮助。以下是选择欧洲和非洲后的问题。请注意,Africa 显示为当前选定的项目,因为这是最后选择的值。

【问题讨论】:

  • API 文档不建议将Node 插入Combobox 的项目。 A warning about inserting Nodes into the ComboBox items list。因此,可以通过为 ComboBox 的项目创建数据模型来解决,该项目具有图像和标签字符串,带有 cellfactory。
  • @monolith52 如果你能告诉我如何使用单元工厂来生成图像和字符串,那就太好了。我无法让它工作,所以我试着这样做。

标签: java javafx combobox javafx-8


【解决方案1】:

正如 cmets 中指出的那样:API 文档不建议将 Node 插入到 Combobox 的项目中。

您的ComboBox 只能存储String 值:

ComboBox<String> comboBox = new ComboBox<>();
comboBox.setItems(FXCollections.observableArrayList("asia", "europe", "america"));

然后您可以编写一个ListCell 实现,例如:

class MyListCell extends ListCell<String> {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (item == null || empty)
            setGraphic(null);
        else {
            Image image = new Image(getClass().getResourceAsStream(item + ".png"));
            ImageView imageView = new ImageView(image);
            imageView.setFitHeight(25);
            imageView.setFitWidth(25);
            setGraphic(new HBox(imageView, new Label(item)));
        }

        setText("");
    }

}

然后使用这个实现在下拉列表中显示HBoxes:

comboBox.setCellFactory(param -> new MyListCell());

并显示在ComboBox 本身:

comboBox.setButtonCell(new MyListCell());

注意:通常ComboBox不应该存储字符串值,而是代表大陆的类的实例,例如封装大陆名称和图像路径的Continent

【讨论】:

  • 像魅力一样工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多