Monday 26 October 2020

JavaFX: css hello world

JavaFX supports css styling. In this post, I am going to explain how to apply styles to a UI widget using css styles.

 

Create a css file with all the necessary styles and apply this css style sheet file to the Scene instance.

 

Scene scene = new Scene(stackPane, 500, 500, Color.WHITE);

String cssFile = HelloWorldCss.class.getResource("/hello.css").toExternalForm();

scene.getStylesheets().add(cssFile);

 

Find the below working application.

 

hello.css

#myText {
    -fx-fill: yellow;
    -fx-stroke: darkblue;
    -fx-stroke-width: 2;
	-fx-font-weight: bold; 
	-fx-font-size: 50; 
	-fx-font-family: Verdana; 
	-fx-font-style: italic
}

HelloWorldCss.java

package com.sample.app;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class HelloWorldCss extends Application {

	@Override
	public void start(Stage primaryStage) throws Exception {

		Text text = new Text("Learning JavaFX");
		text.setId("myText");

		StackPane stackPane = new StackPane();
		stackPane.getChildren().addAll(text);

		Scene scene = new Scene(stackPane, 500, 500, Color.WHITE);
		String cssFile = HelloWorldCss.class.getResource("/hello.css").toExternalForm();
		scene.getStylesheets().add(cssFile);

		primaryStage.setTitle("StackPane Demo");
		primaryStage.setScene(scene);
		primaryStage.show();

	}

	public static void main(String args[]) {
		launch(args);
	}
}


Run above application, you will see below screen.




  

Previous                                                    Next                                                    Home

No comments:

Post a Comment