JavaFX: Designing A Button Using CSS

This entry is part 21 of 55 in the series JavaFX

JavaFX supports the standard CSS3 format and this allows us to design JavaFX interface using standard web page design technique.

Let us first create a new file called style.css.

First add a CSS file called style.css as shown in the screenshot below.

css

In our program, we will have to set the scene to use the style sheet using the statement below.

scene.getStylesheets().add("javafxapplication19/style.css");

Once the scene knows the path of the stylesheet, to apply the design to the button, we use a statement similar to below.

btn.getStyleClass().add("button1");
stylesheet
package javafxapplication19;
 
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class JavaFXApplication19 extends Application {
 
    @Override
    public void start(Stage stage) {
 
        stage.setTitle("JavaFX Program!");
 
        StackPane stackpane = new StackPane();
 
        Scene scene = new Scene(stackpane, 300, 250);
        scene.getStylesheets().add("javafxapplication19/style.css");
        stage.setScene(scene);
 
        Button btn = new Button("Codecrawl");
        btn.getStyleClass().add("button1");
 
        stackpane.getChildren().add(btn);
 
        stage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
 
}

button

Here is the style.css file where we have used to set the font and base color of the button.

.button1 {
    -fx-font: 16 arial; 
    -fx-base: #9CB6CF;    
}

 

 

Series Navigation<< JavaFX: Applying Shadow Effect
JavaFX: Applying Drop Shadow Effects To Button >>

Leave a comment

Leave a Reply