Working with descendant selectors

Similar to regular CSS JavaFX supports descendant selectors. You can chain other selectors to limit the scope of the provided style.

Let's slightly enhance the previous example to demonstrate. All the following three styles are applicable to different types of radio buttons in relation to VBox with ID#vb:

/* chapter6/syntax/pseudo-class-demo.css */

/* 1. Only direct children of #vb, note the ">" sign */
#vb > .radio-button { -fx-font-size: 20 }
/* 2. All children of #vb */
#vb .radio-button { -fx-underline: true }
/* 3. All radio buttons */
.radio-button:selected { -fx-text-fill: red }

To better illustrate this, let's use ScenicView (a very useful JavaFX tool that we discussed in Chapter 2, Building Blocks – Shapes, Text, and Controls):

In this screenshot, we can see a SceneGraph and how it affects the applied styles of the similar nodes:

  • The top nodes have a large font (item 1 in CSS) and are underlined (item 2) because they are direct children of the #vb node. 
  • The not direct child radio button is affected only by the underline effect (item 2) because it is a child of VBox but not a direct one.
  • The outside radio button is not affected by items 1 and 2 at all. But as with all radio buttons in this example, it's affected by item 3—bold font on selection.

And here is the code for the preceding screenshot:

// chapter6/syntax/DescendancyDemo.java
public void start(Stage stage) {
VBox vbox = new VBox(10);
vbox.setId("vb");
ToggleGroup group = new ToggleGroup();
for (String title : new String[] {"Cats", "Dogs", "Birds", "Mices"}) {
RadioButton rb = new RadioButton(title);
rb.setToggleGroup(group);
vbox.getChildren().add(rb);
}

RadioButton rbDescendant = new RadioButton("outside");
rbDescendant.setToggleGroup(group);

RadioButton rbDeepDescendant = new RadioButton("not direct child");
rbDeepDescendant.setToggleGroup(group);
// below we are adding a StackPane to make rbDeepDescendant not a direct child of VBox
vbox.getChildren().add(new StackPane(rbDeepDescendant));

VBox hbox = new VBox(10);
hbox.getChildren().addAll(vbox, rbDescendant);
Scene scene = new Scene(hbox, 300, 250);
scene.getStylesheets().add(getClass().getResource("selectors-demo.css").toExternalForm());
stage.setTitle("Descendancy Demo");
stage.setScene(scene);
stage.show();
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.60.158