The source code is in gist.
JavaFX chart only provides 8 colors. If there are more than 8 series, the colors are reused. As an example, below chart has 11 series.
Notice that the colors are restarted after the 8th. Watermelons has the same color with Apples, Pineapples with Lemons and Coconuts with Oranges.
Let’s find out what styles applied to the series. ScenicView gives what we need here.
After comparing the series styles, the conclusion is we need to change the default-color-x
style of series that the index is bigger than 7 (the index of 8th series is 7) with our own colors. The legend items should be adjusted as well.
First, define the css style. In this example, we will provide ten colors. But since there are already 8 provided by JavaFX, we need to define 2 styles only.
.default-color8.chart-bar { -fx-bar-fill: #babdb6; } .default-color9.chart-bar { -fx-bar-fill: #4e9a06; }
Next, after initializing the BarChart
object, redefined colors for each series.
/** * Set Series color */ for (int i = 0; i < barChartData.size(); i++) { for (Node node : chart.lookupAll(".series" + i)) { node.getStyleClass().remove("default-color" + (i % 8)); node.getStyleClass().add("default-color" + (i % 10)); } } /** * Set Legend items color */ int i = 0; for (Node node : chart.lookupAll(".chart-legend-item")) { if (node instanceof Label && ((Label) node).getGraphic() != null) { ((Label) node).getGraphic().getStyleClass().remove("default-color" + (i % 8)); ((Label) node).getGraphic().getStyleClass().add("default-color" + (i % 10)); } i++; }
The result is
Since there are 11 series while provided colors only 10, Watermelons and Oranges has the same color. For full source code, please get it here.