Search code examples
javacsssvgjavafxfxml

JavaFX/CSS Display an svg shape on the right side of a combo box list cell


I'm looking to create a combo box whom selected item should set its text bold and display a tick at the right side of the list cell (the tick icon is a SVG):

enter image description here

Currently in my code the tick takes all the available space:

enter image description here

Here is my CSS:

.combo-box {
    -fx-background-color: transparent;
    -fx-border-color:     #44494F
    -fx-border-width:     1px
}

.combo-box .arrow {
    -fx-background-color: white;
    -fx-shape: -arrow;
}

.combo-box:showing .arrow {
    -fx-rotate: 180;
}

.combo-box .list-cell {
    -fx-font-size: 10px;
    -fx-text-fill: white;
}

.combo-box-popup .list-view {
    -fx-background-color: #2F353D;
}

.combo-box-popup .list-view .list-cell {
    -fx-background-color: #2F353D;
    -fx-border-width:     0px
}

.combo-box-popup .list-view .list-cell:filled:selected, .combo-box-popup .list-view .list-cell:filled:selected:hover{
    -fx-font-weight: bold;
    -fx-shape:       "m184.405 461.013-184.405-184.405 24.354-24.354 160.051 160.051 332.279-332.279 24.354 24.354z";
}

.combo-box-popup .list-view .list-cell:filled:hover{
    -fx-background-color: #393E44;
}

Is there a way to put the tick on the right side using only CSS ? Even if not, how to achieve that ?


Solution

  • As @jewelsea suggested in the comments, you can supply a custom CellFactory to handle the size:

    ComboBox<String> cb = new ComboBox<>();
    
    cb.setCellFactory(lv -> {
        final ListCell<String> cell = new ListCell<>() {
            @Override 
            public void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                setText(item != null ? item : null);
            }
        };
        Region icon = new Region();
        icon.getStyleClass().add("icon");
        
        cell.setGraphic(icon);
        cell.setGraphicTextGap(20);
        return cell;
    });
    

    You can set the size and style in css:

    .combo-box-popup .list-view .list-cell .icon {
        -fx-min-width: 10;
        -fx-pref-width: 10;
        -fx-max-width: 10;
        
        -fx-min-height: 10;
        -fx-pref-height: 10;
        -fx-max-height: 10;
        
        -fx-shape: "m184.405 461.013-184.405-184.405 24.354-24.354 160.051 160.051 332.279-332.279 24.354 24.354z";
        -fx-background-color: white;
    }
    
    .combo-box-popup .list-view .list-cell {
        -fx-content-display: text-only;
    }
    
    .combo-box-popup .list-view .list-cell:filled:selected {
        -fx-content-display: right;
    }
    

    Output:

    ComboBox