๐ JavaFX Tutorial: Using CSS Styling
๐ฏ Goal
In this tutorial, you will learn:
- How to create a CSS file
- How to connect it to your JavaFX app
- How to style UI components (Button, Label, etc.)
๐จ What is JavaFX CSS?
JavaFX uses a CSS system very similar to web CSS.
โ You can style:
- Colors ๐จ
- Fonts ๐ค
- Sizes ๐
- Backgrounds ๐งฑ
- Hover effects ๐ฑ๏ธ
๐ 1. Create a CSS File
Create a file inside your resources folder:
src/main/resources/org/example/testingtoturials/style.css
Example:
.root {
-fx-background-color: #0f172a;
}
.label {
-fx-text-fill: white;
-fx-font-size: 16px;
}
.button {
-fx-background-color: #3b82f6;
-fx-text-fill: white;
-fx-background-radius: 8;
}
.button:hover {
-fx-background-color: #2563eb;
}
๐ 2. Connect CSS to Your Application
Modify your HelloApplication class:
Scene scene = new Scene(fxmlLoader.load(), 320, 240);
// Add this line ๐
scene.getStylesheets().add(
HelloApplication.class.getResource("style.css").toExternalForm()
);
stage.setScene(scene);
๐ก Explanation
getStylesheets().add()loads the CSS filetoExternalForm()converts it to a usable path
๐ฏ 3. Styling Components
๐น Style by Type (Global)
.button {
-fx-font-size: 14px;
}
๐ Applies to all buttons
๐น Style by ID
In FXML:
<Button fx:id="myButton" text="Click Me"/>
In CSS:
#myButton {
-fx-background-color: red;
}
๐ # targets a specific element
๐น Style by Class
In FXML:
<Button text="Save" styleClass="primary-button"/>
In CSS:
.primary-button {
-fx-background-color: green;
}
๐ . is for reusable styles
โจ 4. Example (Full)
FXML
<VBox alignment="CENTER" spacing="20"
xmlns:fx="http://javafx.com/fxml"
fx:controller="org.example.testingtoturials.HelloController">
<Label text="Welcome!" styleClass="title"/>
<Button text="Click Me" styleClass="primary-button"/>
</VBox>
CSS
.root {
-fx-background-color: #111827;
}
.title {
-fx-text-fill: #f9fafb;
-fx-font-size: 20px;
}
.primary-button {
-fx-background-color: #10b981;
-fx-text-fill: white;
-fx-background-radius: 10;
}
.primary-button:hover {
-fx-background-color: #059669;
}
๐ง Important Notes
- JavaFX CSS properties start with
-fx- - Not all web CSS properties work โ ๏ธ
- You can inspect components using Scene Builder ๐
โ ๏ธ Common Mistakes
- โ Wrong file path โ CSS not applied
- โ Forgetting
toExternalForm() - โ Using normal CSS properties (like
colorinstead of-fx-text-fill) - โ Not linking CSS to the Scene
๐งช Summary
CSS makes your UI beautiful and modern
Attach it using
scene.getStylesheets()Use:
.classโ reusable styles#idโ specific elementtypeโ global styling