FirstStyles demonstration

In this demonstration, we will apply a CSS file to a JavaFX application, changing the styles of several buttons and a root node of the scene:

/* chapter6/basics/style.css */
.root {
-fx-background-color: lightblue;
-fx-padding: 10px;
}
.button {
-fx-background-color: white
}

Note that all JavaFX CSS properties have the -fx prefix to be clearly distinguished from web CSS ones. JavaFX CSS and web CSS share syntax and property names and look very similar but JavaFX developers deliberately made styles and classes different in order to avoid any compatibility issues. 

JavaFX CSS is described in detail in the JavaFX CSS Reference Guide, which can be found here: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html. In that document, you can search for a class you need to style and see all applicable CSS properties.

In the preceding example, .root refers to the root element of the scene and .button to all instances of the Button class.

Now, let's use this CSS in the application:

// chapter6/basics/FirstStyles.java
public void start(Stage stage) {
VBox root = new VBox(10);
Scene scene = new Scene(root, 300, 250);


Button btnLoad = new Button("Load CSS");
btnLoad.setOnAction((ActionEvent event) -> {
// this means take css from the same folder as a current class
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
});

    Button btnUnload = new Button("Unoad CSS");
btnUnload.setOnAction((ActionEvent event) -> {
scene.getStylesheets().clear();
});

root.getChildren().addAll(btnLoad, btnUnload);
stage.setTitle("Hello CSS!");
stage.setScene(scene);
stage.show();
}

Text marked in bold dynamically loads a CSS file and applies it to the scene. Without CSS, our app will look as follows:

And with CSS, you can see different background colors and padding:

If you are using an IDE, make sure you are running Clean and Build after each CSS change as the IDE doesn't always track CSS changes and may not update the output build folder or JAR file.
..................Content has been hidden....................

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