How to dynamically change line style in JavaFX 2.0 line chart?


Question

In our JavaFX project we need a line chart. I can easy stylize the whole chart and series using CSS, but content of our chart can change dynamically:

  1. number of series and their displaying order depends on user actions and his data. Each series represents a concrete data category and the each category has its own style, eg. category A is shown as a dotted line and category B is shown as a dashed line. The chart can contain 0 or more series for each category,

  2. style of series depends on data values too, eg. series line over the average is red, and below is blue.

How to do it in JavaFX?

1
10
3/19/2012 6:19:44 PM

Accepted Answer

  1. number of series and their displaying order depends on user actions and his data.

The number of series displayed and the display order can be modified by changing the ObservableList of series which you passed to the chart's setData() call. As the chart listens for changes to the list, as the backing list changes, the chart is automatically updated to reflect the changes.

each category has its own style, eg. category A is shown as a dotted line and category B is shown as a dashed line.

This can done by determining which series in the chart is in which category, looking up all nodes related to the series via the node lookupAll(cssStyleSelector) function and applying a new custom style to the series which matches the style for the category. Dotted and dashed lines can be styled via css by setting the -fx-stroke-dash-array css property. Alternately, rather than a lookup you can dynamically change the css styleclass assigned to nodes via modifying the ObservableList returned from getStyleClass().

style of series depends on data values too, eg. series line over the average is red, and below is blue.

This is similar to how the dotted and dashed lines are displayed, but instead the color of the lines are modifed by the -fx-stroke css property and the modification depends on the average values calculated for the series.

To demonstrate the above points, I created a sample solution for this question here: https://gist.github.com/2129306

9
3/20/2012 8:05:46 PM

I did it like this, thought it was pretty handy. Note: This apparently works on LineCharts but not ScatterCharts.

 Series<Number, Number> series = new Series<>();
 ...
 series.nodeProperty().get().setStyle("-fx-stroke-width: 1px;");

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon