Customizing JavaFX labels with CSS styling
Write a JavaFX program that constructs a UI with labels. Use CSS to change the font family, size, color, and alignment of the text in the labels.
Sample Solution:
JavaFx Code:
Explanation:
In the exercise above the JavaFX code creates a simple application that displays three labeled elements vertically using a VBox layout. The labels are styled using CSS.
The code is explained briefly below:
- Setting up the UI: The start method initializes a JavaFX window (Stage) with the title "Styled Labels". Three labels (Label) labeled as "Label 1", "Label 2", and "Label 3" are created.
- Assigning IDs for CSS Styling: IDs are set for the labels using setId() method to allow applying CSS styling to these specific labels.
- Layout Structure: The labels are placed in a vertical box (VBox) layout with a spacing of 12 pixels between each label using the VBox constructor.
- CSS Styling: The scene (Scene) loads an external CSS file (styles.css) using getStylesheets().add() to apply styling to the labels based on their IDs.
- Launching the Application: The main method launches the JavaFX application by calling launch(args).
Sample Output:
Flowchart:

Java Code Editor:
Previous: Creating a JavaFX form with styled text fields.
Next: Customizing JavaFX toggle buttons with CSS styling.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics