java - 选择项目后组合框中的图像消失

标签 java javafx

我创建了一个组合框并向其中添加了标签,这样我就可以使用带有图标的文本,但在选择项目后图标消失,我做错了什么?

选择之前:

enter image description here

选择后:

enter image description here

ObservableList<Label> booruChoices = FXCollections.observableArrayList();
booruChoices.add(new Label("Gelbooru", new ImageView("https://gelbooru.com/favicon.ico")));
booruChoices.add(new Label("Danbooru", new ImageView("https://i.imgur.com/7ek8bNs.png")));
booruSelector.getItems().addAll(booruChoices);
booruSelector.setCellFactory(param -> {
    return new ListCell<Label>() {
        @Override
        public void updateItem(Label item, boolean empty) {
            super.updateItem(item, empty);

            if (item != null) {
                setGraphic(item.getGraphic());
                setText(item.getText());
            }
        }
    };
});

最佳答案

第一个答案不是你想要的,我的错误。 您对 ComboBox 中的单元格和 ComboBox 的按钮使用相同的 ImageView。一个ImageView只能显示在一个地方。 您需要为 ComboBox 中的每个单元格创建一个图形节点。对于 ComboBox 来说,Label 不是一个好的项目类型,因为它表示 UI 节点而不是数据对象。 以下是保存数据的类的示例:

public class MyData {
    private String name;
    private Image image;

    public MyData(String name, String imageUrl) {
        this.name = name;
        this.image = new Image(imageUrl);
    }

    public String getName() {
        return name;
    }

    public Image getImage() {
        return image;
    }
}

然后您可以使用该类创建一个ComboBox:

ComboBox<MyData> comboBox = new ComboBox<>();
MyData data1 = new MyData("Gelbooru", "https://gelbooru.com/favicon.ico");
MyData data2 = new MyData("Danbooru", "https://i.imgur.com/7ek8bNs.png");
comboBox.getItems().addAll(data1, data2);
comboBox.setCellFactory(param -> new ListCell<>() {
    final ImageView graphicNode = new ImageView();

    @Override
    protected void updateItem(MyData item, boolean empty) {
        super.updateItem(item, empty);
        if (item == null || empty) {
            setText(null);
            setGraphic(null);
            graphicNode.setImage(null);
        } else {
            setText(item.getName());
            graphicNode.setImage(item.getImage());
            setGraphic(graphicNode);
        }
    }
});

关于java - 选择项目后组合框中的图像消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59841920/

相关文章:

java - Java中如何加速443端口扫描

java - 如何按照JavaFx显示多个矩形

java - native 代码数据库可以进行逆向工程吗?

javascript - JavaFX 容器内的 Java、JavaFx : Inserting a HTML&JS(static, 无互联网)项目

java - 无法从 JavaFX 中的 MenuItem 获取场景

Java/javaFX Hangman 帮助对错过的尝试进行倒计时

java - 扩展堆栈库

java - 无类 已注册云端点

java - 为 java 1.6 切换类型字符串

java - 在 JavaFX 中切换主题