在JavaFX中实现只读样式? [英] Implement read-only style in JavaFX?

查看:1196
本文介绍了在JavaFX中实现只读样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有具有不同状态的实体(控件或属性),这些实例可以由CSS着色。

I would like to have entity (control or property) which has different states, which are possible to be colored by CSS.

例如,关于TextField可以包含两种类型的值,正常和错误。一旦它包含错误的值,它应该显示红色。但实际的颜色应该可以从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.

这是否可以实现?

Styleable * 接口或类,但它们看起来像能够接受任何样式。

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?

推荐答案

您可以使用 Node.pseudoClassStateChanged

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);
        }
    }
});

使用类似这样的css:

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.

这篇关于在JavaFX中实现只读样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆