I am trying to style my JavaFX linechart, but can't find any way to set color to specific series. I know, that I can style via CSS, but I can't find how to set ID or CLASS to my series.
Can anyone give me a clue on:
jewelsea's answer seems to state that you have to put a style-class on every node of the series. I'm using the following code to style the series of an area chart and only assign a class to the node associated with the series.
Example code is in Scala, but should be easy to translate.
When creating the series, I add a series-specific style class:
val s = new XYChart.Series[Number, Number]() //create a new series
s.setName(seriesName) //set its name (display in legend)
s.getNode.getStyleClass.add("series-" + seriesName) //add specific style class
Then inside the CSS file I do the following to change the fill color of the series butterwings
:
.series-butterwings *.chart-series-area-fill{
-fx-fill: #aab597;
}
This works, because the node for the series area is below the series node (which is a group in case of area chart).
How to set a color to linecharts?
Here's a simple way to AreaChart or LineChart
XYChart chart = new AreaChart();
Series series = new Series();
chart.getData().add(series);
Node fill = series.getNode().lookup(".chart-series-area-fill"); // only for AreaChart
Node line = series.getNode().lookup(".chart-series-area-line");
Color color = Color.RED; // or any other color
String rgb = String.format("%d, %d, %d",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255));
fill.setStyle("-fx-fill: rgba(" + rgb + ", 0.15);");
line.setStyle("-fx-stroke: rgba(" + rgb + ", 1.0);");
In general the way preferred way to style charts is without code, using only css stylesheets as jschoen recommends. Additionally, if further customization is required, you can use css lookups from code to dig into the the nodes generated from series data and apply various additional css styling.
Here is information about dynamically changing a JavaFX line chart style and a sample program to go with the answer. In the sample app, all of the additional css styling is done via a setStyle call from code. Using a similar lookup technique, you could get access to the series nodes to apply an appropriate stylesheet styleclass rather than a setStyle call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With