Implement read-only style in JavaFX?

大兔子大兔子 提交于 2019-12-20 05:41:57

问题


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?


回答1:


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.




回答2:


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

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