A very powerful and often underestimated feature of JavaFX is its CSS Color Derivation.
But let us start at the beginning by explaining two prerequisites:
- The Default JavaFX 8 Theme (Modena) only defines a few colors statically in its stylesheet. The rest is derived by JavaFX’s color functions (ladder and derive - see the CSS Reference) or referenced as color variables.
- If you start to apply a custom styles to a Node in the scenegraph, these styles will also be applied to all children of this Node (if applicable). So changing a color variable on a single node will change the corresponding colors, derived colors and referenced colors on all child nodes in the scenegraph, but not on any of its parent nodes.
If we combine both together we can create these three Buttons with ease (the first one is a regular one, just to show the default theme):
But let’s start with the Java Code for our little example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Essentially we create some buttons, stuff them into a ToolBar and it to the Scene. Additionally we assign some style classes in order to do the color magic later on.
Doing the old school way we would have ended up editing all of the buttons colors.
But if we take a closer look at the default button colors..
1 2 3 4
..you may see the colors are referenced, and as you may guess they are derived of the aforementioned base colors.
For example look at the border color, defined in the root of the modena theme:
1 2 3
So to put all of this together, we only need these simple rules in our CSS file:
1 2 3 4 5 6
What happens is that we changed the base color on each of the buttons. Now JavaFX is clever enough to detect that with a different base color, the derived colors for each of the buttons (and its children) need an update.
Wait there’s more
Now this was a very basic example, but to give you another example we can switch the base color of the root container to create our own “dark theme”:
1 2 3
This will result in this darker version of our sample application:
Using derived colors throughout your application will make your life a lot easier!