m.prime
m.prime

Reputation: 67

How to add images as an option in a combo box in Java FX

I tried adding images to a combo box to show them as options but once i select the images they turn white when the dropdown opens again to select them they turn white.

ImageView img1 = new ImageView(getClass().getResource("item1.png").toExternalForm());
ImageView img2 = new ImageView(getClass().getResource("item2.jpg").toExternalForm());
ImageView img3 = new ImageView(getClass().getResource("item3.jpg").toExternalForm());
img1.setFitHeight(60);
img1.setFitWidth(60);
img1.setPreserveRatio(true);
img2.setFitHeight(60);
img2.setFitWidth(60);
img2.setPreserveRatio(true);
img3.setFitHeight(60);
img3.setFitWidth(60);
img3.setPreserveRatio(true);
combobox.getItems().addAll(img1,img2,img3);

the choices work only once and they turn white when i try to select them again.

Upvotes: 1

Views: 690

Answers (1)

SlipshodDread
SlipshodDread

Reputation: 36

You are not setting the elements properly. You need to utilise the setCellFactory() method of the combobox in order for list items to be generated correctly as the Items are expected to be a list of relevant data, not Nodes. The ListCell object can then have setGraphic(ImageView) called upon itw, and updates that element of the list to the specified image.

Here is some example code from an old project of mine, which is actually designed for a ListView but will work exactly the same as the ComboBox:

pieceData = FXCollections.observableArrayList("Boot", "Car", "Dog", "Hat", "Iron",
                                                  "Ship", "Thimble", "Wheelbarrow");
pieceSelection.setItems(pieceData);

pieceSelection.setCellFactory(e -> new ListCell<String>() {
    private ImageView view = new ImageView();
    @Override
    public void updateItem(String name, boolean empty) {
        super.updateItem(name, empty);
        if(empty) {
            setGraphic(null);
        }
        else {
            view.setImage(new Image("whatever the filepath to your image is"));
            // Add other set up for ImageView dimensions etc
            setGraphic(view);
        }
    }
});

Bear in mind that this only displayed the images, because the method setText(String) is required to be called in order to have any text displayed.

Also as kleopatra stated, you should read a basic JavaFX tutorial since this type of thing is well documented and relatively simple.

Upvotes: 2

Related Questions