通过JavaFX 8中的代码访问和更改CSS伪类的值 [英] Access and change of the value of a css pseudoclass via code in JavaFX 8

查看:159
本文介绍了通过JavaFX 8中的代码访问和更改CSS伪类的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以访问诸如.text-area *.text {}之类的CSS伪类,更重要的是可以通过代码更改它们的值? textArea.setStyle()在这种情况下似乎不适用. 描述问题: 我试图在单击按钮时更改TextArea的文本对齐方式. 我知道可以通过

Is it possible to access css pseudo-classes such as .text-area *.text {} and more importantly change values of them via code? textArea.setStyle() does not seem to be applicable in this case. To describe the problem: I'm trying to change the text-alignment of an TextArea on a button click. I know it's possible to change the alignment via

.text-area *.text {
-fx-text-alignment: center;
}

但是如何将其绑定到按钮单击上呢?

but how can i bind that to a button click?

推荐答案

请注意,CSS选择器.text-area *.text

Note that there are no pseudoclasses used in the CSS selector .text-area *.text

使用的选择器部分是类选择器(.text.text-area),通用选择器(*)和后代选择器(.text-area*.text之间的).

The selector parts used are class selectors (.text, .text-area), the universal selector (*) and the descendant selector ( between .text-area and *.text).

但是,有多种方法可以通过代码设置对齐方式:

However there are multiple ways to set the alignment from code:

可以使用伪类来区分居中的TextArea和非居中的TextArea.

A pseudoclass could be used to distinguish centered TextAreas from non-centered ones.

PseudoClass centered = PseudoClass.getPseudoClass("centered");

// activate pseudoclass
textArea.pseudoClassStateChanged(centered, true);

// deactivate pseudoclass
textArea.pseudoClassStateChanged(centered, false);

CSS

.text-area:centered .text {
    -fx-text-alignment: center;
}

类似地,可以使用一个类,但是它不太方便,因为可以多次添加类.

Similarly a class could be used, but it's less convenient, since classes could be added multiple times.

CSS变量的值是从父节点继承的,这就是为什么您可以使用它以内联样式将其分配给子节点的属性的原因:

Values of CSS variables are inherited from parent nodes, which is why you could use it to assign a property of a child node using inline style:

CSS

.text-area {
    /* default value of variable */
    alignment: left;
}

.text-area .text {
    /* use variable for TextArea child */
    -fx-text-alignment: alignment;
}

// overwrite variable from inline style
textArea.setStyle("alignment: center;");

使用lookupAll

查找Node

这是最糟糕的选择,因为它需要像TextArea这样的Control来创建其skin,这要等到布局才会发生,这意味着代码要等到第一次布局后才能起作用. /p>

Finding the Nodes using lookupAll

This is the worst alternative, since it requires Controls like TextArea to have their skin created, which does not happen until layout, which means the code won't work until the first layout pass.

// find children matching .text and assign set the property for each one
textArea.lookupAll(".text").forEach(n -> n.setStyle("-fx-text-alignment: center;"));

这篇关于通过JavaFX 8中的代码访问和更改CSS伪类的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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