Im new to FXML and i'm building an application. Now i'm running into a problem that i cant fix.
I defined a combobox in the FXML and created the necesarry assocation in the controller class. But i want to add images to this combobox.
Still after hours of searching on google i'm still not able to fix this.
Can you guys please help me with a "simple" example on how to reach my goal?
Many thanks!
My current code is: (sure that there is an easier way to do this, but it works!)
ImageView img1 = new ImageView("Layout/nl.png");
ImageView img2 = new ImageView("Layout/en.png");
AnimalBoxLanguage.getItems().addAll(img1, img2);
AnimalBoxLanguage.setCellFactory(new Callback<ListView<ImageView>, ListCell<ImageView>>() {
@Override
public ListCell<ImageView> call(ListView<ImageView> p) {
return new ListCell<ImageView>() {
private final ImageView rectangle;
{
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
rectangle = new ImageView();
}
@Override
protected void updateItem(ImageView item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
} else {
rectangle.setImage(item.getImage());
setGraphic(rectangle);
}
}
};
}
});
You need to customize the CellFactory of the ComboBox to maintain the visualization of the items in the box. See this link for a short example.
To make the image visible in the control area (after you select one item), you have to set the button cell of the combobox to one of your cells. JavaFX will automatically update them accordingly. Basically what you have to do is when you set up the combobox with your custom cellfactory is:
mycombobox.setButtonCell(myCellFactory.call(null));
Also have a look at the documentation regarding this.