Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
872 views
Welcome To Ask or Share your Answers For Others

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...