Brad Turek
Brad Turek

Reputation: 2832

How do Attribute Selectors work in JavaFX?

In the JavaFX CSS Reference Guide, it's made clear that

JavaFX Cascading Style Sheets (CSS) is based on the W3C CSS version 2.1 [1] with some additions from current work on version 3 [2].

In the JCRG, they often link directly to the W3C's CSS Reference Guide, and such is the case when they talk about selectors.

In the JCRG, they mention Type Selectors, Class Selectors, and ID Selectors—they even go so far as to say that they don't support structural pseudo-classes—but nothing is said about Attribute Selectors.

If JavaFX supports them, how do they work? What does JavaFX consider an attribute? I thought the CSS engine might look at the attributes in the FXML, but then not all scene graphs originate from FXML.

Upvotes: 3

Views: 423

Answers (1)

James_D
James_D

Reputation: 209330

FXML attributes simply set properties on the corresponding objects. There are no "property selectors" per se, but some nodes will set pseudoclasses if and only if certain properties are set (these are documented in the reference guide you link). So the bottom line is that there is no direct equivalent of attribute selectors unless they map directly to a pseudoclass.

Note, of course, that you can always observe a property and set/unset a custom pseudoclass if you need to support CSS based on a property. So it is always possible to recast an attribute selector as a pseudoclass.

So, e.g. suppose you wanted to style a text field differently if it has an "alignment=CENTER_RIGHT" attribute. You could do

TextField textField = new TextField();
PseudoClass rightAligned = PseudoClass.getPseudoClass("right-aligned");
textField.alignmentProperty().addListener((obs, oldAlignment, newAlignment) -> 
    textField.pseudoClassStateChanged(rightAligned, newAlignment == Pos.CENTER_RIGHT));

Then in your CSS you just need

.text-field:right-aligned {
    /* style rules */
}

Upvotes: 2

Related Questions