4

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).

DVarga
  • 21,311
  • 6
  • 55
  • 60
geef
  • 65
  • 1
  • 2
  • 8
  • Once the image is selected I'd like to see that image in the comboBox, now it's only the image path(String) – geef Jun 25 '16 at 16:47

1 Answers1

5

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.

DVarga
  • 21,311
  • 6
  • 55
  • 60
  • 1
    Also adjust the hight constraints to make the `ImageView` fit into the `ComboBox`: `comboBox.setMinHeight(50);`. Furthermore recreating `ImageView`s should be avoided. Setting the `image` property to `null` should result in nothing being displayed and allow you to avoid recreating the node. Also for small images this many not be an issue, but for larger images I'd recommend using a cache (e.g. `Map>`) and loading the image in the background... – fabian Jun 25 '16 at 16:58