1

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?

SilverMonkey
  • 1,003
  • 7
  • 16

1 Answers1

3

Note that there are no pseudoclasses used in the CSS selector .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:

Using a Pseudo-class

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.

Using a custom CSS variable

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

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;"));
fabian
  • 80,457
  • 12
  • 86
  • 114