Marcin Marcin - 5 months ago 172
Java Question

JavaFX ComboBox Image

I am trying to create a

ComboBox
that will display a preview of selected
Image
, but the
ComboBox
displays the string value instead.

The only way appears to work is to create
ComboBox
of
Node
, but that causes once selected option disappear from the drop down menu, would appreciate if someone has any suggestions.

My code below:

String notOnLine = "file:Java1.png";
String onLine = "file:Java2.png";
ObservableList<String> options = FXCollections.observableArrayList();
options.addAll(notOnLine, onLine);
final ComboBox<String> comboBox = new ComboBox(options);
comboBox.setCellFactory(c -> new StatusListCell());


and the
ListCell
:

public class StatusListCell extends ListCell<String> {
protected void updateItem(String item, boolean empty){
super.updateItem(item, empty);
setGraphic(null);
setText(null);
if(item!=null){
ImageView imageView = new ImageView(new Image(item));
imageView.setFitWidth(40);
imageView.setFitHeight(40);
setGraphic(imageView);
setText("a");
}
}

}


preview

I'd like the image to be displayed in the
ComboBox
itself once the list is closed. Right now it's just showing the URL (e.g.
file:Java1.png
).

Answer

You can specify the buttonCellProperty of the ComboBox:

comboBox.setButtonCell(new StatusListCell());

The button cell is used to render what is shown in the ComboBox 'button' area.

Comments