English 中文(简体)
JavaFX - Application
  • 时间:2024-12-22

JavaFX - Apppcation


Previous Page Next Page  

In this chapter, we will discuss the structure of a JavaFX apppcation in detail and also learn to create a JavaFX apppcation with an example.

JavaFX Apppcation Structure

In general, a JavaFX apppcation will have three major components namely Stage, Scene and Nodes as shown in the following diagram.

JavaFX Apppcation Structure

Stage

A stage (a window) contains all the objects of a JavaFX apppcation. 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 Apppcation class (explained in the next section).

A stage has two parameters determining its position namely Width and Height. It is spanided as Content Area and Decorations (Title Bar and Borders).

There are five types of stages available −

    Decorated

    Undecorated

    Transparent

    Unified

    Utipty

You have to call the show() method to display the contents of a stage.

Scene

A scene represents the physical contents of a JavaFX apppcation. 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.

Scene Graph and Nodes

A scene graph is a tree-pke 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.

    UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.

    Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.

    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 earper a node is of three types −

    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 pst of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state appped on the group will be appped 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.

    Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Elppse, 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 cppped to the scene and any alteration in the size of the scene will not affect the layout of the scene.

Creating a JavaFX Apppcation

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

Apppcation Class

The Apppcation class of the package javafx.apppcation is the entry point of the apppcation in JavaFX. To create a JavaFX apppcation, 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 apppcation using the launch() method. This method internally calls the start() method of the Apppcation class as shown in the following program.

pubpc class JavafxSample extends Apppcation {  
   @Override     
   pubpc void start(Stage primaryStage) throws Exception { 
      /* 
      Code for JavaFX apppcation. 
      (Stage, scene, scene graph) 
      */       
   }         
   pubpc static void main(String args[]){           
      launch(args);      
   } 
} 

Within the start() method, in order to create a typical JavaFX apppcation, you need to follow the steps given below −

    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 stage and add the scene to the stage and display the contents of the stage.

Preparing the Scene Graph

As per your apppcation, 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 pst object 
ObservableList pst = root.getChildren(); 
       
//Setting the text object as a node  
pst.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 apppcation.

    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 apppcation.

    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 apppcation.

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 pst = pane.getChildren(); 
pst.add(NodeObject);

WebView − This node manages the web engine and displays its contents.

Following is a diagram representing the node class hierarchy of JavaFX.

WebView

Preparing the Scene

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);

Preparing the Stage

This is the container of any JavaFX apppcation and it provides a window for the apppcation. 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 Apppcation 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().

    Attach the scene object to the stage using the setScene() method.

    Display the contents of the scene using the show() method as shown below.

//Setting the title to Stage. 
primaryStage.setTitle("Sample apppcation"); 
       
//Setting the scene to Stage 
primaryStage.setScene(scene); 
       
//Displaying the stage 
primaryStage.show();

Lifecycle of JavaFX Apppcation

The JavaFX Apppcation class has three pfe cycle methods, which are −

    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 apppcation.

    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 apppcation.

Since the launch() method is static, you need to call it from a static context (main generally). Whenever a JavaFX apppcation is launched, the following actions will be carried out (in the same order).

    An instance of the apppcation class is created.

    Init() method is called.

    The start() method is called.

    The launcher waits for the apppcation to finish and calls the stop() method.

Terminating the JavaFX Apppcation

When the last window of the apppcation is closed, the JavaFX apppcation is terminated imppcitly. You can turn this behavior off by passing the Boolean value “False” to the static method setImppcitExit() (should be called from a static context).

You can terminate a JavaFX apppcation exppcitly using the methods Platform.exit() or System.exit(int).

Example 1 – Creating an Empty Window

This section teaches you how to create a JavaFX sample apppcation which displays an empty window. Following are the steps −

Step 1: Creating a Class

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

pubpc class JavafxSample extends Apppcation {  
   @Override     
   pubpc void start(Stage primaryStage) throws Exception {      
   }    
} 

Step 2: Creating a Group Object

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();

Step 3: Creating a Scene Object

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);

Step 4: Setting the Title of the Stage

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 Apppcation as shown below.

primaryStage.setTitle("Sample Apppcation");

Step 5: Adding Scene to the Stage

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);

Step 6: Displaying the Contents of the Stage

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

primaryStage.show();

Step 7: Launching the Apppcation

Launch the JavaFX apppcation by calpng the static method launch() of the Apppcation class from the main method as follows.

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

Example

The following program generates an empty JavaFX window. Save this code in a file with the name JavafxSample.java

import javafx.apppcation.Apppcation; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.paint.Color; 
import javafx.stage.Stage;  

pubpc class JavafxSample extends Apppcation { 
   @Override     
   pubpc 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 Apppcation"); 
   
      //Adding the scene to Stage 
      primaryStage.setScene(scene); 
       
      //Displaying the contents of the stage 
      primaryStage.show(); 
   }    
   pubpc 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.

Sample Apppcation Plain

Example 2 – Drawing a Straight Line

In the previous example, we have seen how to create an empty stage, now in this example let us try to draw a straight pne using the JavaFX pbrary.

Following are the steps −

Step 1: Creating a Class

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

pubpc class DrawingLine extends Apppcation {
   @Override     
   pubpc void start(Stage primaryStage) throws Exception {     
   }    
} 

Step 2: Creating a Line

You can create a pne in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape, instantiate this class as follows.

//Creating a pne object         
Line pne = new Line();

Step 3: Setting Properties to the Line

Specify the coordinates to draw the pne 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.

pne.setStartX(100.0); 
pne.setStartY(150.0); 
pne.setEndX(500.0); 
pne.setEndY(150.0);

Step 4: Creating a Group Object

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(pne);

Step 5: Creating a Scene Object

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);

Step 6: Setting the Title of the Stage

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 Apppcation as follows.

primaryStage.setTitle("Sample Apppcation");

Step 7: Adding Scene to the Stage

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);

Step 8: Displaying the Contents of the Stage

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

primaryStage.show();

Step 9: Launching the Apppcation

Launch the JavaFX apppcation by calpng the static method launch() of the Apppcation class from the main method as follows.

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

Example

The following program shows how to generate a straight pne using JavaFX. Save this code in a file with the name JavafxSample.java.

import javafx.apppcation.Apppcation; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.shape.Line; 
import javafx.stage.Stage;  

pubpc class DrawingLine extends Apppcation{ 
   @Override 
   pubpc void start(Stage stage) { 
      //Creating a pne object 
      Line pne = new Line(); 
         
      //Setting the properties to a pne 
      pne.setStartX(100.0); 
      pne.setStartY(150.0); 
      pne.setEndX(500.0); 
      pne.setEndY(150.0); 
         
      //Creating a Group 
      Group root = new Group(pne); 
         
      //Creating a Scene 
      Scene scene = new Scene(root, 600, 300); 
         
      //Setting title to the scene 
      stage.setTitle("Sample apppcation"); 
         
      //Adding the scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of a scene 
      stage.show(); 
   }      
   pubpc 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 pne as shown below.

Drawing Line

Example 3 – Displaying Text

We can also embed text in JavaFX scene. This example shows how to embed text in JavaFX.

Following are the steps −

Step 1: Creating a Class

Create a Java Class and inherit the Apppcation class of the package javafx.apppcation and implement the start() method of this class as follows.

pubpc class DrawingLine extends Apppcation {  
   @Override     
   pubpc void start(Stage primaryStage) throws Exception {     
   } 
}

Step 2: Embedding Text

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();

Step 3: Setting the Font

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)); 

Step 4: Setting the Position of the Text

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); 

Step 5: Setting the text to be added

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");

Step 6: Creating a Group Object

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)

Step 7: Creating a Scene Object

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);

Step 8: Setting the Title of the Stage

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 Apppcation as shown below.

primaryStage.setTitle("Sample Apppcation");

Step 9: Adding Scene to the Stage

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);

Step 10: Displaying the Contents of the Stage

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

primaryStage.show();

Step 11: Launching the Apppcation

Launch the JavaFX apppcation by calpng the static method launch() of the Apppcation class from the main method as follows.

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

Example

Following is the program to display text using JavaFX. Save this code in a file with name DisplayingText.java.

import javafx.apppcation.Apppcation; 
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; 
         
pubpc class DisplayingText extends Apppcation { 
   @Override 
   pubpc 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 pst object 
      ObservableList pst = root.getChildren(); 
       
      //Setting the text object as a node to the group object 
      pst.add(text);       
               
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300); 
       
      //Setting title to the Stage 
      stage.setTitle("Sample Apppcation"); 
         
      //Adding scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of the stage 
      stage.show(); 
   }   
   pubpc 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.

JavaFX Window Displaying Text Advertisements