首页 > 解决方案 > JavaFX/CSS 在组合框列表单元格的右侧显示 svg 形状

问题描述

我正在寻找创建一个组合框,所选项目应将其文本设置为粗体并在列表单元格的右侧显示一个勾号(勾号图标是 SVG):

在此处输入图像描述

目前在我的代码中,勾号占用了所有可用空间:

在此处输入图像描述

这是我的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;
}

有没有办法只使用 CSS 将勾选放在右侧?即使没有,如何实现?

标签: javacsssvgjavafxfxml

解决方案


正如@jewelsea 在评论中建议的那样,您可以提供一个自定义CellFactory来处理大小:

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;
});

您可以在以下位置设置大小和样式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;
}

输出:

组合框


推荐阅读