Changing individual line chart series color JavaFX

2020-05-09 01:38发布

问题:

I have a window that has three different line charts in it. I am trying to set the color of each line chart series individually. Right now I have a css file that has something like this:

.default-color0.chart-series-line { -fx-stroke: blue }
.default-color1.chart-series-line { -fx-stroke: black }

What this does is set the colors of series in each chart. For example, if I have a line chart that has two series, one would be blue, the other would be black. But with this setting, all three charts with one series default to blue.

What I am trying to achieve is setting the series individually, so that my first line chart has someColor1, the second line chart has someColor2, etc.

I have tried many things, and searched all over the internet, but I have either seen "guesses" which do not work, or ways to set the default through css. Does anyone have a solution to this issue?

I am trying to set the style using lineChart.setStyle("-fx-stroke: green"); for example.

回答1:

To reference nodes individually (instead of grouped by class) in a CSS file, you need to add an id to the node:

LineChart<Number, Number> chart1 =  ... ;
LineChart<Number, Number> chart2 =  ... ;
LineChart<Number, Number> chart3 =  ... ;

chart1.setId("chart1");
chart2.setId("chart2");
chart3.setId("chart3");

Obviously, you can choose more meaningful ids that describe what each chart is.

Then in your CSS you can do

#chart1 .chart-series-line { -fx-stroke: blue }
#chart2 .chart-series-line { -fx-stroke: black }
#chart3 .chart-series-line { -fx-stroke: green }


标签: java css javafx