JavaFX ComboBox background color by selected item

I would like to change background of a ComboBox based on selected item.

For example: if selected first item then background should be green, if second one is selected then red.

Is this possible?

If you want to just set the color of the ComboBox itself and not the items of the ComboBox inside the drop-down list, you can create a custom binding between the buttonCellProperty and the valueProperty of the ComboBox to implement the custom coloring.


This example colors the ComboBox to green if the first item is selected, to red if the second item is selected, and leaves the coloring as it is otherwise.

Update:The background color of the arrow button of the ComboBox is also colored now, for that the lookup method can be used to get the arrow button: StackPane arrowButton = (StackPane) combo.lookup(".arrow-button"); .

ComboBox combo = new ComboBox();
combo.setItems(FXCollections.observableArrayList("First", "Second", "Third", "Fourth"));

combo.buttonCellProperty().bind(Bindings.createObjectBinding(() -> {

    int indexOf = combo.getItems().indexOf(combo.getValue());

    Color color = Color.TRANSPARENT;

    switch (indexOf) {
    case 0: color = Color.GREEN; break;
    case 1: color = Color.RED; break;
    default: break;

    final Color finalColor = color;

    // Get the arrow button of the combo-box
    StackPane arrowButton = (StackPane) combo.lookup(".arrow-button");

    return new ListCell() {

        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);

            if (empty || item == null) {
            } else {
                setBackground(new Background(new BackgroundFill(finalColor, CornerRadii.EMPTY, Insets.EMPTY)));

            // Set the background of the arrow also
            if (arrowButton != null)

}, combo.valueProperty()));

The result is like:


1)If you want to color the items also in the drop-down list, you can pick the solution from other answers here.

2)If you do not display String s but items that are able to store also the color of the item, the solution is even shorter, just use the color of the selected item in updateItem method rather than calculating your own color.

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » JavaFX ComboBox background color by selected item

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录