JavaFX - Application

In this chapter, we will discuss the structure of a JavaFX application in detail and also learn to create a JavaFX application with an example.
In general, a JavaFX application will have three major components namely Stage, Scene and Nodes as shown in the following diagram.
A stage (a window) contains all the objects of a JavaFX application. It is represented by Stage class of the package javafx.stage. The primary stage is created by the platform itself. The created stage object is passed as an argument to the start() method of the Application class (explained in the next section).
A stage has two parameters determining its position namely Width and Height. It is divided as Content Area and Decorations (Title Bar and Borders).
There are five types of stages available  −
Decorated
Undecorated
Transparent
Unified
Utility
You have to call the show() method to display the contents of a stage.
A scene represents the physical contents of a JavaFX application. It contains all the contents of a scene graph. The class Scene of the package javafx.scene represents the scene object. At an instance, the scene object is added to only one stage.
You can create a scene by instantiating the Scene Class. You can opt for the size of the scene by passing its dimensions (height and width) along with the root node to its constructor.
A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In contrast, a node is a visual/graphical object of a scene graph.
A node may include −
Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.
Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.
UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.
UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.
Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.
Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.
Media elements such as Audio, Video and Image Objects.
Media elements such as Audio, Video and Image Objects.
The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super class of all the nodes.
As discussed earlier a node is of three types −
Root Node − The first Scene Graph is known as the Root node.
Root Node − The first Scene Graph is known as the Root node.
Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types −

Group − 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. Any transformation, effect state applied on the group will be applied to all the child nodes.
Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control.
WebView − This node manages the web engine and displays its contents.


Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types −
Group − 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. Any transformation, effect state applied on the group will be applied to all the child nodes.
Group − 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. Any transformation, effect state applied on the group will be applied to all the child nodes.
Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control.
Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control.
WebView − This node manages the web engine and displays its contents.
WebView − This node manages the web engine and displays its contents.
Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes.
Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes.
It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the nodes will be clipped to the scene and any alteration in the size of the scene will not affect the layout of the scene.
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.
The Application class of the package javafx.application is the entry point of the application in JavaFX. To create a JavaFX application, you need to inherit this class and implement its abstract method start(). In this method, you need to write the entire code for the JavaFX graphics
In the main method, you have to launch the application using the launch() method. This method internally calls the start() method of the Application class as shown in the following program.
public class JavafxSample extends Application {  
   @Override     
   public void start(Stage primaryStage) throws Exception { 
      /* 
      Code for JavaFX application. 
      (Stage, scene, scene graph) 
      */       
   }         
   public static void main(String args[]){           
      launch(args);      
   } 
} 
Within the start() method, in order to create a typical JavaFX application, you need to follow the steps given below −
Prepare a scene graph with the required nodes.
Prepare a scene graph with the required nodes.
Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it.
Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it.
Prepare a stage and add the scene to the stage and display the contents of the stage.
Prepare a stage and add the scene to the stage and display the contents of the stage.
As per your application, you need to prepare a scene graph with required nodes. Since the root node is the first node, you need to create a root node. As a root node, you can choose from the Group, Region or WebView.
Group − A Group node is represented by the class named Group which belongs to the package javafx.scene, you can create a Group node by instantiating this class as shown below.
Group root = new Group();

The getChildren() method of the Group class gives you an object of the ObservableList class which holds the nodes. We can retrieve this object and add nodes to it as shown below.
//Retrieving the observable list object 
ObservableList list = root.getChildren(); 
       
//Setting the text object as a node  
list.add(NodeObject); 

We can also add Node objects to the group, just by passing them to the Group class and to its constructor at the time of instantiation, as shown below.
Group root = new Group(NodeObject);

Region − It is the Base class of all the JavaFX Node-based UI Controls, such as −
Chart − This class is the base class of all the charts and it belongs to the package javafx.scene.chart.
This class has two sub classes, which are − PieChart and XYChart. These two in turn have subclasses such as AreaChart, BarChart, BubbleChart, etc. used to draw different types of XY-Plane Charts in JavaFX.
You can use these classes to embed charts in your application.

Chart − This class is the base class of all the charts and it belongs to the package javafx.scene.chart.
This class has two sub classes, which are − PieChart and XYChart. These two in turn have subclasses such as AreaChart, BarChart, BubbleChart, etc. used to draw different types of XY-Plane Charts in JavaFX.
You can use these classes to embed charts in your application.
Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane, DialogPane, etc. This class belong to a package that is called as − javafx.scene.layout.
You can use these classes to insert predefined layouts in your application.

Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane, DialogPane, etc. This class belong to a package that is called as − javafx.scene.layout.
You can use these classes to insert predefined layouts in your application.
Control − It is the base class of the User Interface controls such as Accordion, ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc. This class belongs to the package javafx.scene.control.
You can use these classes to insert various UI elements in your application.

Control − It is the base class of the User Interface controls such as Accordion, ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc. This class belongs to the package javafx.scene.control.
You can use these classes to insert various UI elements in your application.
In a Group, you can instantiate any of the above-mentioned classes and use them as root nodes, as shown in the following program.
//Creating a Stack Pane 
StackPane pane = new StackPane();       
       
//Adding text area to the pane  
ObservableList list = pane.getChildren(); 
list.add(NodeObject);

WebView − This node manages the web engine and displays its contents.
Following is a diagram representing the node class hierarchy of JavaFX.
A JavaFX scene is represented by the Scene class of the package javafx.scene. You can create a Scene by instantiating this class as shown in the following cod block.
While instantiating, it is mandatory to pass the root object to the constructor of the scene class.
Scene scene = new Scene(root);

You can also pass two parameters of double type representing the height and width of the scene as shown below.
Scene scene = new Scene(root, 600, 300);

This is the container of any JavaFX application and it provides a window for the application. It is represented by the Stage class of the package javafx.stage. An object of this class is passed as a parameter of the start() method of the Application class.
Using this object, you can perform various operations on the stage. Primarily you can perform the following −
Set the title for the stage using the method setTitle().
Set the title for the stage using the method setTitle().
Attach the scene object to the stage using the setScene() method.
Attach the scene object to the stage using the setScene() method.
Display the contents of the scene using the show() method as shown below.
Display the contents of the scene using the show() method as shown below.
//Setting the title to Stage. 
primaryStage.setTitle("Sample application"); 
       
//Setting the scene to Stage 
primaryStage.setScene(scene); 
       
//Displaying the stage 
primaryStage.show();

The JavaFX Application class has three life cycle methods, which are −
start() − The entry point method where the JavaFX graphics code is to be written.
start() − The entry point method where the JavaFX graphics code is to be written.
stop() − An empty method which can be overridden, here you can write the logic to stop the application.
stop() − An empty method which can be overridden, here you can write the logic to stop the application.
init() − An empty method which can be overridden, but you cannot create stage or scene in this method.
init() − An empty method which can be overridden, but you cannot create stage or scene in this method.
In addition to these, it provides a static method named launch() to launch JavaFX application.
Since the launch() method is static, you need to call it from a static context (main generally). Whenever a JavaFX application is launched, the following actions will be carried out (in the same order).
An instance of the application class is created.
An instance of the application class is created.
Init() method is called.
Init() method is called.
The start() method is called.
The start() method is called.
The launcher waits for the application to finish and calls the stop() method.
The launcher waits for the application to finish and calls the stop() method.
When the last window of the application is closed, the JavaFX application is terminated implicitly. You can turn this behavior off by passing the Boolean value “False” to the static method  setImplicitExit() (should be called from a static context).
You can terminate a JavaFX application explicitly using the methods  Platform.exit() or  System.exit(int).
This section teaches you how to create a JavaFX sample application which displays an empty window. Following are the steps −
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 {  
   @Override     
   public void start(Stage primaryStage) throws Exception {      
   }    
} 
In the start() method creates a group object by instantiating the class named Group, which belongs to the package javafx.scene, as follows.
Group root = new Group();

Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step.
In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.
Scene scene = new Scene(root,600, 300);

You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter.
Using the primaryStage object, set the title of the scene as Sample Application as shown below.
primaryStage.setTitle("Sample Application");

You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as shown below.
primaryStage.setScene(scene);

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

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);      
}  
The following program generates an empty JavaFX window. Save this code in a file with the name JavafxSample.java
import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.paint.Color; 
import javafx.stage.Stage;  

public class JavafxSample extends Application { 
   @Override     
   public void start(Stage primaryStage) throws Exception {            
      //creating a Group object 
      Group group = new Group(); 
       
      //Creating a Scene by passing the group object, height and width   
      Scene scene = new Scene(group ,600, 300); 
      
      //setting color to the scene 
      scene.setFill(Color.BROWN);  
      
      //Setting the title to Stage. 
      primaryStage.setTitle("Sample Application"); 
   
      //Adding the scene to Stage 
      primaryStage.setScene(scene); 
       
      //Displaying the contents of the stage 
      primaryStage.show(); 
   }    
   public static void main(String args[]){          
      launch(args);     
   }         
} 
Compile and execute the saved java file from the command prompt using the following commands.
javac JavafxSample.java 
java JavafxSample

On executing, the above program generates a JavaFX window as shown below.
In the previous example, we have seen how to create an empty stage, now in this example let us try to draw a straight line using the JavaFX library.
Following are the steps −
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 DrawingLine extends Application {
   @Override     
   public void start(Stage primaryStage) throws Exception {     
   }    
} 
You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape, instantiate this class as follows.
//Creating a line object         
Line line = new Line();

Specify the coordinates to draw the line on an X-Y plane by setting the properties startX, startY, endX and endY, using their respective setter methods as shown in the following code block.
line.setStartX(100.0); 
line.setStartY(150.0); 
line.setEndX(500.0); 
line.setEndY(150.0);

In the start() method create a group object by instantiating the class named Group, which belongs to the package javafx.scene.
Pass the Line (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −
Group root = new Group(line);

Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root) that was created in the previous step.
In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.
Scene scene = new Scene(group ,600, 300);

You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter.
Using the primaryStage object, set the title of the scene as Sample Application as follows.
primaryStage.setTitle("Sample Application");

You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows.
primaryStage.setScene(scene);

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

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);      
} 
The following program shows how to generate a straight line using JavaFX. Save this code in a file with the name JavafxSample.java.
import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.shape.Line; 
import javafx.stage.Stage;  

public class DrawingLine extends Application{ 
   @Override 
   public void start(Stage stage) { 
      //Creating a line object 
      Line line = new Line(); 
         
      //Setting the properties to a line 
      line.setStartX(100.0); 
      line.setStartY(150.0); 
      line.setEndX(500.0); 
      line.setEndY(150.0); 
         
      //Creating a Group 
      Group root = new Group(line); 
         
      //Creating a Scene 
      Scene scene = new Scene(root, 600, 300); 
         
      //Setting title to the scene 
      stage.setTitle("Sample application"); 
         
      //Adding the scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of a scene 
      stage.show(); 
   }      
   public static void main(String args[]){ 
      launch(args); 
   } 
} 
Compile and execute the saved java file from the command prompt using the following commands.
javac DrawingLine.java 
java DrawingLine

On executing, the above program generates a JavaFX window displaying a straight line as shown below.
We can also embed text in JavaFX scene. This example shows how to embed text in JavaFX.
Following are the steps −
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 DrawingLine extends Application {  
   @Override     
   public void start(Stage primaryStage) throws Exception {     
   } 
}
You can embed text into a JavaFX scene by instantiating the class named Text which belongs to a package javafx.scene.shape, instantiate this class.
You can instantiate this class by passing text to be embedded, in String format Or, you can create text object using the default constructor as shown below.
//Creating a Text object 
Text text = new Text();

You can set font to the text using the setFont() method of the Text class. This method accepts a font object as parameters. Set the font of the given text to 45 as shown below.
//Setting font to the text 
text.setFont(new Font(45)); 

You can set the position of the text on the X-Y plane by setting the X,Y coordinates using the respective setter methods setX() and setY() as follows.
//setting the position of the text 
text.setX(50); 
text.setY(150); 

You can set the text to be added using the setText() method of the Text class. This method accepts a string parameter representing the text to be added.
text.setText("Welcome to Tutorialspoint");
In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene.
Pass the Text (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −
Group root = new Group(text)

Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step.
In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.
Scene scene = new Scene(group ,600, 300);

You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter.
Using the primaryStage object, set the title of the scene as Sample Application as shown below.
primaryStage.setTitle("Sample Application");

You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows.
primaryStage.setScene(scene);

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

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);      
} 
Following is the program to display text using JavaFX. Save this code in a file with name DisplayingText.java.
import javafx.application.Application; 
import javafx.collections.ObservableList; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.stage.Stage; 
import javafx.scene.text.Font; 
import javafx.scene.text.Text; 
         
public class DisplayingText extends Application { 
   @Override 
   public void start(Stage stage) {       
      //Creating a Text object 
      Text text = new Text(); 
       
      //Setting font to the text 
      text.setFont(new Font(45)); 
       
      //setting the position of the text 
      text.setX(50); 
      text.setY(150);          
      
      //Setting the text to be added. 
      text.setText("Welcome to Tutorialspoint"); 
         
      //Creating a Group object  
      Group root = new Group(); 
       
      //Retrieving the observable list object 
      ObservableList list = root.getChildren(); 
       
      //Setting the text object as a node to the group object 
      list.add(text);       
               
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300); 
       
      //Setting title to the Stage 
      stage.setTitle("Sample Application"); 
         
      //Adding scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of the stage 
      stage.show(); 
   }   
   public static void main(String args[]){ 
      launch(args); 
   } 
} 
Compile and execute the saved java file from the command prompt using the following commands.
javac DisplayingText.java 
java DisplayingText

On executing, the above program generates a JavaFX window displaying text as shown below.

    33 Lectures 
     7.5 hours 

 Syed Raza

    64 Lectures 
     12.5 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    20 Lectures 
     4 hours 

 Emenwa Global, Ejike IfeanyiChukwu
 Print
 Add Notes
 Bookmark this page