I have a LineChart and I want to change the -fx-background-color of its -chart-plot-background property. I want to do it without using an external CSS file (and only through the code, since I want to be able to change a property dynamically). Unfortunately, the following lines fail to work:
linechart.setStyle("-chart-plot-background(-fx-background-color: red;)");
linechart.setStyle("-chart-plot-background{-fx-background-color: red;}");
The error reads:
Jun 21, 2023 7:04:17 PM javafx.css.CssParser parse
WARNING: CSS Error parsing '*{-chart-plot-background(-fx-background-color: red;)}: Expected RBRACE at [1,45]
or
Jun 21, 2023 7:04:17 PM javafx.css.CssParser parse
WARNING: CSS Error parsing '*{-chart-plot-background{-fx-background-color: red;}}: Expected RBRACE at [1,45]
How can we tackle this problem?
The string you pass to
setStyle()should be a syntactically valid CSS rule, or set of rules separated by;. The text you are passing is not the correct syntax.You can use external CSS and change colors dynamically using "looked-up colors" (see the documentation for a definition). In brief, do:
and then you can change it dynamically with
Depending on your use-case, a custom pseudoclass may also be appropriate. This would also allow you to change properties other than colors dynamically. For the specific example you posted:
and then in code you can do
As pointed out in a comment, both of these approaches have limitations. The "looked-up color" approach can only be used for colors (JavaFX CSS does not support other types of CSS variable), and custom CSS PseudoClasses can only be used for a discrete set of values.
As a last resort, for use-cases that do not fit into those two, you can use a CSS lookup. Note that the
lookup(...)method will return null unless a CSS pass has been made, but since you are dynamically applying these styles, this should have happened at the point you need to apply the dynamic style. Again, for the example you cite:If for any reason you need to do this before the chart has CSS applied in the natural lifecycle of the scene graph (this really shouldn't happen; your external CSS (or just the system default) can define the initial/default CSS state, and the dynamic changes should only be invoked after some event occurs, which should necessarily be after the component is displayed), you can force CSS to be applied via calls to
linechart.applyCSS();andlinechart.layout();.