Tuesday 20 October 2020

JavaFX: Hello World application

  Step 1: Extend 'javafx.application.Application' class and override start method.

public class HelloWorld extends Application {

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

}

 

Application class is responsible for launching and stopping of the application. This class starts JavaFX application thread.

 

Step 2: We should create a scene and attach it to the Stage instance.

 

Group group = new Group();

Scene scene = new Scene(group, 500, 500, Color.AZURE);

primaryStage.setScene(scene);

 

In the above example, ‘group’ is the root node of the scene graph.

 

Step 3: Once you attach the Scene instance to Stage instance, you can call the show method of stage, to show this window on screen.

 

primaryStage.show();

 

Step 4: You can set title to your stage using ‘setTitle’ method

primaryStage.setTitle("Hello World");

 

Step 5: To launch the application, call the launch method available in Application class.

 

Find the below working application, you will see following kind of window.

 

HelloWorld.java

package com.sample.app;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class HelloWorld extends Application {

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

		primaryStage.setTitle("Hello World");

		Group group = new Group();

		Scene scene = new Scene(group, 500, 500, Color.AZURE);

		primaryStage.setScene(scene);

		primaryStage.show();

	}

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

}

 

Run HelloWorld application, you will see below window.


Scene graph of above application looks like below.



 

Previous                                                    Next                                                    Home

No comments:

Post a Comment