简体   繁体   English

在JavaFX中实现只读样式?

[英]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. 我想要具有不同状态的实体(控件或属性),可以通过CSS对其进行着色。

For example, regard TextField, which can contain two sort of values, normal and erroneous. 例如,以TextField为例,它可以包含两种值,正常值和错误值。 Once it contain erroneous value, it should be displayed "red". 一旦包含错误值,它应该显示为“红色”。 But the actual color should be definable from CSS. 但是实际颜色应该可以从CSS中定义。

Is this possible to implement? 这可能实现吗?

I found plenty of Styleable* interfaces or classes, but they are looked like able to accept any style. 我发现了很多Styleable*接口或类,但是它们看起来可以接受任何样式。

Can I write and entity, which derives it's style from the value? 我可以编写和实体,从价值中得出风格吗?

You can use Node.pseudoClassStateChanged : 您可以使用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: 用这样的CSS:

.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. 虽然老实说,我不能完全确定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. 为此,您需要在CSS中添加多种颜色样式,然后可以使用以下代码更改样式类。

 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. 例如,在TextField发生动作事件时,您可以检查用户在TextField中输入了哪个值,如果输入的值是“错误的”,则获取文本字段的对象,并使用上面的代码为其设置样式类名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM