每个选定项目的 JavaFX ComboBox 背景颜色

标签 java javafx combobox javafx-8

我想根据所选项目更改ComboBox 的背景。

例如:如果选择第一项,则背景应为绿色,如果选择第二项,则背景应为红色。

这可能吗?

最佳答案

如果您只想设置 ComboBox 本身的颜色,而不是下拉列表中 ComboBox 的项目,则可以在两者之间创建自定义绑定(bind)buttonCellPropertyvalueProperty ComboBox 的用于实现自定义着色。

示例

如果选择第一个项目,此示例将 ComboBox 颜色设置为绿色,如果选择第二个项目,则将颜色设置为红色,否则保持原样。

更新:ComboBox 的箭头按钮的背景颜色现在也已着色,因为 lookup方法可用于获取箭头按钮:StackPane arrowButton = (StackPane)combo.lookup(".arrow-button");

ComboBox<String> 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<String>() {

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

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

            // Set the background of the arrow also
            if (arrowButton != null)
                arrowButton.setBackground(getBackground());
        }

    };
}, combo.valueProperty()));

结果如下:

enter image description here

注释

1)如果您还想为下拉列表中的项目着色,您可以从此处的其他答案中选择解决方案。

2) 如果您不显示String,但项目也能够存储项目的颜色,则解决方案更短,只需使用颜色updateItem 方法中所选项目的颜色,而不是计算您自己的颜色。

关于每个选定项目的 JavaFX ComboBox 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38760184/

相关文章:

C# WPF ComboBox - 允许每个列表只选择一次项目

java - 性能方面,Guava 库有多好?

java - ListView 项目不会出现在 JavaFx 应用程序中

java - 如何在 selenium webdriver 中使用 CSS 选择器 `contains` 获取元素

JavaFX 编译警告 - "uses unchecked or unsafe operations"- 原始数据类型?

java - 将 CSS 应用于 FXML 中的堆叠图表

vba - 排序组合框 VBA

windows - 如何在 winforms 中重新绑定(bind)组合框?

java - 没有找到合适的驱动程序调用 getConnection

java - 在这个例子中如何解决代码重复,我引入继承来实际解决代码重复