NO_ob
NO_ob

Reputation: 113

Image in ComboBox disappearing after item is selected

I have created a ComboBox and added labels to it so I can have text with an icon but the icons disappear after an item is selected, What have I done wrong?

Before Selection:

enter image description here

After Selection:

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());
            }
        }
    };
});

Upvotes: 3

Views: 364

Answers (1)

Miss Chanandler Bong
Miss Chanandler Bong

Reputation: 4258

The first answer was not what you're asking for, my mistake. You are using the same ImageView for a cell in the ComboBox and for the ComboBox's button. An ImageView can be displayed in one place only. You need to create a graphic node for each cell in your ComboBox. Label is not a good item type for a ComboBox as it represents a UI node not a data object. Here is an example of a class that holds your data:

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;
    }
}

Then you can creat a ComboBox using that class:

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);
        }
    }
});

Upvotes: 4

Related Questions