Question

I have a TextField styled by changing styleClass when its value is valid/invalid but there is a great problem. When the value becomes valid I still should change the TextField once more to make the styleClass be applied. I tried with applyCss() method just after, but it didn't work :(.

    if(!valid){
        field.getStyleClass().add("invalid-field");//Works excellent
    } else {
        field.getStyleClass().remove("invalid-field");//Doesn't work up to the time textProperty doesn't change once again
        field.applyCss();
Was it helpful?

Solution

One common cause of these bugs is that you may have added the "invalid-field" style class more than once. (Remember, getStyleClass() returns a List<String>, not a Set<String>.) So you should probably take steps to make sure the style class is only added once, or take steps to remove all occurrences when you remove it.

I like to do both (where I come from, we call this a "belt and braces approach").

ObservableList<String> styleClasses = field.getStyleClass();
if(!valid)
    if( ! styleClass.contains("invalid-field")){
        styleClass.add("invalid-field");
    } 
} else {
    // remove all occurrences:
    styleClass.removeAll(Collections.singleton("invalid-field"));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top