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?
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.
On change event of particular property, you can change style class of that entity(control or property) in order to apply multiple colors.
For this, you need to add multiple color styles in CSS
and then you can change the Style Class by using below code.
textfield.getStyleClass().add("red");
For example, on action event of TextField, you can check which value user have entered in TextField and if entered value is "erroneous" then get the object of text field and set the style class name to it using above code.
来源:https://stackoverflow.com/questions/36883838/implement-read-only-style-in-javafx