I'm working on a JavaFX application with numerous CSS files. These CSS files are unique in that they don't extend control classes like .vbox {}
or .button {}
; instead, they define custom node CSS properties using IDs (e.g., #custom-node-name {}
).
I'm currently faced with two possible approaches for integrating these CSS files into my application, and I'm concerned about their performance implications.
Option 1: Apply All CSS Files Globally
In this approach, I would add all of these CSS files to the scene or the scene's root Parent
and reference the custom node properties through style classes that match the node's type. For example, if it's a button, I'd use #custom-button
, and for a text field, #custom-text-field
.
The potential issue here is that every node in my scene graph would have to search through every CSS stylesheet to find the style class it requires, which could be problematic in terms of performance.
Option 2: Apply CSS Files to Individual Nodes
In this alternative, I'd add the stylesheet to each individual node that needs access to the custom CSS property and then apply the corresponding style class to it. Similarly, if my Pane
node contains multiple child nodes that require the same style class, I'd add the CSS file to the Pane
, and all child nodes within it can access the style class.
The issue with this approach is that I might end up adding the same CSS stylesheet multiple times to the scene graph. For instance, different parts of the application might require the same styling for different nodes, resulting in redundant stylesheet references.
My Question: Which approach is the most performant way of handling CSS stylesheets and style classes in a JavaFX application? Should I go with Option 1, Option 2, or is there a better approach that balances performance and maintainability?
Solution:
The best approach is to apply the CSS files globally for globally things, like button styling, etc.
If you have scene specific CSS, e.g. there is one button on a specific scene, which needs height 500px, then put this into a separate CSS file and add it to the scene.
Reasons for that:
Rules of thumb: