Is it possible to change the color of the items inside a ComboBox
in JavaFX?
I want to change the background color of each item to black and its text to white, and to green and white when hovering.
@FXML
private ComboBox<String> govs;
public void initialize() {
ObservableList<String> options = FXCollections.observableArrayList(
"Ariana",
"Beja",
"Ben Arous",
"Bizerte",
"Gabès"
);
govs.setItems(options);
}
Since this cannot be done by applying CSS rules to the node, you have to supply your own cell factory implementation to the combobox.
comboBox.setCellFactory(param -> new ComboBoxListCell<String>() {{
setTextFill(Color.WHITE);
Background blackBackground = new Background(new BackgroundFill(Color.BLACK, null, null));
Background greenBackground = new Background(new BackgroundFill(Color.GREEN, null, null));
setBackground(blackBackground);
setOnMouseEntered(event -> {
setBackground(greenBackground);
});
setOnMouseExited(event -> {
setBackground(blackBackground);
});
}});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.