我想根据所选项目更改ComboBox
的背景。
例如:如果选择第一项,则背景应为绿色,如果选择第二项,则背景应为红色。
这可能吗?
最佳答案
如果您只想设置 ComboBox
本身的颜色,而不是下拉列表中 ComboBox
的项目,则可以在两者之间创建自定义绑定(bind)buttonCellProperty和 valueProperty 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()));
结果如下:
注释
1)如果您还想为下拉列表中的项目着色,您可以从此处的其他答案中选择解决方案。
2) 如果您不显示String
,但项目也能够存储项目的颜色,则解决方案更短,只需使用颜色updateItem
方法中所选项目的颜色,而不是计算您自己的颜色。
关于每个选定项目的 JavaFX ComboBox 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38760184/