How to use CSS in JavaFX project?

Hello friends!
I hope you guys are familiar now with JavaFX development environment also you have done some hands-on with JavaFX Scene Builder. In this blog, I am going to explain the steps of using CSS in JavaFX project to create great GUI for our project. Please follow the steps given below.
Step 1: First create a project “JavaFX FXML Application” project in NetBeans IDE.


 
Step 2: Once the project is created it will appear in the left menu.
 
 

Step 3: Now create a new folder CSS and create a file with .css extension.

 

Step 4: Now you have to write some code in the following two files:

i) CSS_IN_JAVAFX.java file

ii) newCascadeStyleSheet.css (we just created it in above step)

Adding a Style Sheet

Now copy and paste following lines of code in “CSS_IN_JAVAFX.java” file.

Scene scene = new Scene(root);

scene.getStylesheets().add(“CSS/newCascadeStyleSheet.css”);

Please see the location of CSS file in below screenshot.

 
 
Write CSS code to change the background color of a button in newCascadeStyleSheet.css.
.button {
    -fx-background-color: linear-gradient(#ff5400, #be1d00);
    -fx-background-radius: 30;
    -fx-background-insets: 0;
    -fx-text-fill: white;
}
 


Step 5:
Now save and do the clean build and run the application. And you will see a button on stage with a red background.

 
Thanks For Reading.
 

Leave a Comment