How to create a JavaFX Basic Application?

JavaObject Oriented ProgrammingProgramming

To create a basic JavaFX application follow the steps given below −

Extend the Application class

To create a JavaFX application, you need to instantiate the Application class and implement its abstract method start(). In this method, we will write the code for the JavaFX Application.

Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.

public class JavafxSample extends Application {
   public void start(Stage primaryStage) throws Exception {
   }
}

Create a Group Object

A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order.

In the start() method create a group object by instantiating the javafx.scene.Group class −

Group root = new Group();

Create a Scene Object

A scene graph is a data structure similar to tree, in modern graphical applications it is a collection of nodes. In a JavaFX application the javafx.scene.Scene class holds all the contents of a scene graph.

Instantiate the javafx.scene class, to its constructor, pass the Group object (root), created in the previous step.

Scene scene = new Scene(root,600, 300);

Add the scene object to the Stage

A stage is the top most container of a JavaFX application and it provides a window for the application it is represented by the javafx.stage.Stage class. An object of this is passed as a parameter to the start() method.

Add the Scene object prepared in the previous step to the stage using the setScene() method.

Method.primaryStage.setScene(scene);

Displaying the Contents

Display the contents of the scene using the method named show() of the Stage class as follows.

primaryStage.show();

Launch the Application

Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.

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

Example

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class BasicApplication extends Application {
   public void start(Stage stage) {
      //Instantiating the group class
      Group root = new Group();
      //Instantiating the Scene class
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      //Setting the scene to the Stage
      stage.setScene(scene);
      //Setting Title to the stage
      stage.setTitle("JavFX Basic Application");
      //Displaying the contents of the stage
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 13-Apr-2020 15:19:27
Advertisements