Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javafx

charts

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?

like image 567
Kojak Avatar asked Mar 18 '12 11:03

Kojak


2 Answers

  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

like image 106
jewelsea Avatar answered Nov 20 '22 15:11

jewelsea


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;");
like image 42
Guz Avatar answered Nov 20 '22 15:11

Guz