Search code examples
javacssjavafxstyleable

Implement read-only style in JavaFX?


I would like to have entity (control or property) which has different states, which are possible to be colored by CSS.

For example, regard TextField, which can contain two sort of values, normal and erroneous. Once it contain erroneous value, it should be displayed "red". But the actual color should be definable from CSS.

Is this possible to implement?

I found plenty of Styleable* interfaces or classes, but they are looked like able to accept any style.

Can I write and entity, which derives it's style from the value?


Solution

  • You can use Node.pseudoClassStateChanged:

    TextField tf = new TextField();
    final PseudoClass shortText = PseudoClass.getPseudoClass("short");
    final PseudoClass longText = PseudoClass.getPseudoClass("long");
    tf.textProperty().addListener((observable, oldValue, newValue) -> {
        tf.pseudoClassStateChanged(shortText, false);
        tf.pseudoClassStateChanged(longText, false);
        if (newValue!=null && !newValue.isEmpty()) {
            if (newValue.length() < 5) {
                tf.pseudoClassStateChanged(shortText, true);
            } else {
                tf.pseudoClassStateChanged(longText, true);
            }
        }
    });
    

    With a css like this:

    .text-field:short {
     -fx-background-color: #ffaaaa;
    }
    .text-field:long {
     -fx-background-color: #aaffaa;
    }
    

    Although to be honest I'm not entirely sure what are the pros and cons of Style Class vs. Pseudo Class.