Java combobox how to add icon?
Taking the sample erhun linked in his comment as a starting point, define the ComboBox in fxml as below so that the combo box items include Labels with graphics (these are your "icons").
<ComboBox fx:id="fruitCombo" layoutX="15.0" layoutY="33.0" prefWidth="90.0" promptText="choose">
<items>
<FXCollections fx:factory="observableArrayList">
<Label text="Apple">
<graphic>
<StackPane prefWidth="50">
<ImageView fitHeight="32" preserveRatio="true">
<image>
<Image url="http://uhallnyu.files.wordpress.com/2011/11/green-apple.jpg" preserveRatio="false" smooth="false" />
</image>
</ImageView>
</StackPane>
</graphic>
</Label>
<Label text="Pear">
<graphic>
<StackPane prefWidth="50">
<ImageView fitHeight="32" preserveRatio="true">
<image>
<Image url="http://smoothiejuicerecipes.com/pear.jpg" preserveRatio="false" smooth="false" />
</image>
</ImageView>
</StackPane>
</graphic>
</Label>
<Label text="Orange">
<graphic>
<StackPane prefWidth="50">
<ImageView fitHeight="32" preserveRatio="true">
<image>
<Image url="http://i.i.com.com/cnwk.1d/i/tim/2011/03/10/orange_iStock_000001331357X_540x405.jpg" preserveRatio="false" smooth="false" />
</image>
</ImageView>
</StackPane>
</graphic>
</Label>
</FXCollections>
</items>
</ComboBox>
And in the FruitComboController initialize method, set a custom cell for the button (the simple cell below just takes the text of the seleted item, but you could also include a graphic as well if you liked):
ListCell<Label> buttonCell = new ListCell<Label>() {
@Override protected void updateItem(Label item, boolean isEmpty) {
super.updateItem(item, isEmpty);
setText(item == null ? "" : item.getText());
}
};
fruitCombo.setButtonCell(buttonCell);
The above is just one way to do this. Alternately (and perhaps preferably) you could define a cell factory for your ComboBox
as Sebastian points out in his answer.
Output of the modified sample:
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.