Saturday, June 18, 2016

45. CSS

An external css file can be used to style different kinds of elements. They help reduce Java code, since we do not have to use too many setters.


In the code, we create an id for button1 which is referenced by the css file.


package ex45;
 
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
 
public class Ex45 extends Application {
 
    @Override
    public void start(Stage primaryStage) {
 
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Label lab1 = new Label("label1");
        Label lab2 = new Label("label2");
        button1.setId("button1");
        VBox root = new VBox(50, button1, button2, lab1, lab2);
        Scene scene = new Scene(root, 400, 600);
        
        String css = this.getClass()
                .getResource("cssFile.css").toExternalForm(); 
        scene.getStylesheets().add(css);
        
        root.setAlignment(Pos.CENTER);
        
        primaryStage.setTitle("Example 45. CSS");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}

This is the css file (cssFile.css). We have a class for all the labels in the program. In addition we have css rules for the id for button1, as well as the root class.


#button1 {
    -fx-font-size: 25px;
    -fx-font-family: verdana;
    -fx-background-color: yellow;
}

.label {
    -fx-font-size: 50px;
    -fx-font-family: georgia;
    -fx-background-color: red;
    -fx-text-fill: #f80
}

.root {
    -fx-background-color: honeydew;
}

This is the output:


No comments:

Post a Comment