Search code examples
javacssjavafxpseudo-class

How to add class or pseudoclass programmatically to custom control in JavaFX?


In JavaScript world it is often set element class to denote it's appearance, which is later defined by CSS.

Is this so in JavaFX?

For example, what if I want to color negative value in red in TableView cells? I would not code color directly, but assigned some class to a cell, like "negative" and later would color it into red with CSS.

I found PseudoClass class. Is it intended for this? It is marked "since 8", so is there any more mature API for this?


Solution

  • If you want to add a style to a Node that you can toggle on and off, a PseudoClass is indeed the correct way to do it. It was indeed added in JavaFX 8.0, but that is the current stable version, so it is a mature API. Note that this creates a pseudoclass (:classname in CSS), not a "normal" class (.classname in CSS).

    If you have a Node you want to style (lets call it node), you can use PseudoClass like this:

    node.pseudoClassStateChanged(PseudoClass.getPseudoClass("negative"), true);
    

    Do the same thing, except with false as the second argument, to turn it off again.