Implement read-only style in JavaFX?

僤鯓⒐⒋嵵緔 提交于 2019-12-02 08:23:51
Itai

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!