Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set specific color to JavaFX XYChart.Series?

Tags:

javafx-2

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:

  1. How to set a color to linecharts?
  2. How to set a css class to series?
like image 679
Yurish Avatar asked Jun 22 '12 09:06

Yurish


3 Answers

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).

like image 111
ziggystar Avatar answered Oct 17 '22 04:10

ziggystar


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);");
like image 43
Nazariy Demyanovskyi Avatar answered Oct 17 '22 04:10

Nazariy Demyanovskyi


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.

like image 37
jewelsea Avatar answered Oct 17 '22 02:10

jewelsea