Often I want to do some simple styling for JavaFX components as for example changing the background of a tree table cell. I could not find any alternative to
cell.setStyle("-fx-background-color: blue");
For the same table cell I also want to change the color of text:
cell.setTextFill(Color.WHITE);
Writing the second method call is imho far less error-prone than fiddling around with strings in setStyle("???")
, not to mention using .css
files for styling. @jewelsea told me that I'm missing something here. Can anyone give me a hint?
Almost(?) all CSS properties correspond to properties in the corresponding objects, though the naming is not always identical. You can use the documentation to discover the corresponding Java properties.
In this specific case, note that -fx-background-color
is a CSS property of Region
. Referring to the Javadocs for Region
you will see there is a background
property requiring a parameter of type Background
. In JavaFX 18 and later you can use the static convenience method Background.fill(...)
to create a background given a specific fill (e.g. a color).
So
cell.setBackground(Background.fill(Color.BLUE));
will give the desired result.
Writing the second method call is imho far less error-prone than fiddling around with strings in
setStyle("???")
, not to mention using.css
files for styling.
While the remarks about compile-time checking being absent for CSS are well-taken, there are some benefits to using CSS for styling your application that you should consider. Firstly, it provides a clean separation between style and layout which is difficult to achieve in pure Java code. Secondly, it allows you to globally style your application in a single place (just one .tree-table-cell
rule in your CSS file, instead of replicating calls in every cell factory, for example). Replicating this functionality in Java would require implementing some fairly complex factory patterns for creating your UI components. And thirdly, using CSS gives you the chance to provide application "theming" in a pretty quick and easy way, which again is difficult to achieve in pure Java.
Generally I would recommend an external style sheet for styling your application.