Showing posts with label JavaFX. Show all posts
Showing posts with label JavaFX. Show all posts

Wednesday, December 13, 2023

Unveiling the Power of JavaFX: A Comprehensive Guide

Unveiling the Power of JavaFX: A Comprehensive Guide

Introduction


JavaFX, a cutting-edge technology in the world of software development, stands as a testament to the relentless pursuit of excellence. In this article, we delve into the intricacies of JavaFX, shedding light on its features, applications, and the unparalleled advantages it brings to the table.

Understanding JavaFX


JavaFX is a robust software platform designed by Oracle to facilitate the development and deployment of rich internet applications (RIAs). Leveraging the power of Java, this framework empowers developers to create immersive and visually stunning user interfaces across various platforms.

The Core Features


1. Rich User Interface Components

JavaFX boasts an extensive library of user interface components, enabling developers to craft highly interactive and visually appealing applications. From customizable buttons to advanced charts, the framework provides a versatile set of tools.

2. Multi-Platform Capabilities

One of JavaFX's standout features is its ability to run seamlessly on multiple platforms. Whether it's Windows, macOS, or Linux, the framework ensures a consistent user experience across diverse operating systems.

3. 2D and 3D Graphics

For developers seeking to create graphics-intensive applications, JavaFX delivers on both fronts. The framework supports both 2D and 3D graphics, providing an ideal canvas for building visually striking applications.

Applications of JavaFX


JavaFX finds its application in a myriad of domains, demonstrating its versatility and adaptability.

1. Enterprise Applications

The robustness of JavaFX makes it an ideal choice for developing enterprise-level applications. Its rich set of UI components and seamless integration with Java backend systems ensures a smooth and efficient workflow.

2. Media-Rich Applications

For developers in the multimedia space, JavaFX serves as a game-changer. Its support for audio, video, and animations makes it the go-to framework for creating media-rich applications with ease.

3. Mobile Development

JavaFX isn't confined to desktop environments; it extends its capabilities to mobile development. Developers can leverage JavaFX to create cross-platform mobile applications, simplifying the development process.

Advantages of Choosing JavaFX


When it comes to selecting a framework for your next project, the advantages of JavaFX are hard to ignore.

1. Ease of Integration

JavaFX seamlessly integrates with other Java technologies, allowing developers to leverage the vast ecosystem of Java libraries and frameworks. This ease of integration translates to increased productivity and reduced development time.

2. Modern UI Design

With JavaFX, creating modern and aesthetically pleasing user interfaces becomes a breeze. The framework's CSS styling support facilitates the customization of UI elements, ensuring a visually cohesive application.

3. Performance Optimization

JavaFX is engineered for optimal performance. Its hardware-accelerated graphics pipeline ensures smooth rendering of complex visual elements, contributing to a seamless user experience.

JavaFX vs. Competitors


In a landscape filled with various UI frameworks, JavaFX distinguishes itself with its unique set of features and capabilities.

1. JavaFX vs. Swing

While Swing has been a stalwart in Java GUI development, JavaFX takes the lead with its modern design, improved performance, and enhanced multimedia capabilities. The transition to JavaFX is a natural evolution for developers seeking a contemporary UI experience.

2. JavaFX vs. Java AWT

Compared to the Abstract Window Toolkit (AWT), JavaFX offers a more sophisticated and feature-rich environment. AWT's limitations in UI design are overcome by the versatility and modernity that JavaFX brings to the table.

Conclusion

In conclusion, JavaFX emerges as a powerhouse in the realm of UI development, offering unparalleled features, versatility, and performance. Whether you are a seasoned developer or a newcomer to the programming scene, embracing JavaFX opens the door to a world of possibilities.

Friday, October 27, 2023

Exploring the Versatility of JavaFX

Exploring the Versatility of JavaFX

JavaFX is a versatile and dynamic platform that has revolutionized the world of software development. With its remarkable features and capabilities, it has become an indispensable tool for developers worldwide. In this article, we will delve into the key features of JavaFX that make it a powerful choice for creating cutting-edge applications.

Introducing JavaFX: A Brief Overview


JavaFX is a rich set of graphics and media APIs that provide endless possibilities for creating interactive and visually stunning applications. It is a part of the Java Development Kit (JDK), making it readily accessible for Java developers. Let's explore the exceptional features that set JavaFX apart.

1. Rich User Interface (UI)

JavaFX is renowned for its ability to create captivating user interfaces. Its comprehensive library of UI components allows developers to craft modern and aesthetically pleasing interfaces, enhancing the user experience. From stylish buttons to intricate animations, JavaFX offers a wide range of tools to bring your application to life.

2. Cross-Platform Compatibility

One of JavaFX's standout features is its cross-platform compatibility. Developers can create applications that run seamlessly on various operating systems, including Windows, macOS, and Linux. This versatility saves time and effort, as there's no need to develop separate versions for different platforms.

3. Scene Builder

JavaFX simplifies the UI design process with its Scene Builder tool. This intuitive WYSIWYG editor enables developers to create UI layouts effortlessly by simply dragging and dropping components. It streamlines the development process, reducing the need for extensive coding.

4. Rich Set of Controls

JavaFX provides an extensive array of controls that cater to different application needs. Whether you require tables, charts, or sophisticated text editing, JavaFX has you covered. This versatility allows developers to create diverse applications without the need for third-party libraries.

5. 2D and 3D Graphics

For applications that demand intricate graphics and animations, JavaFX's support for 2D and 3D graphics is invaluable. It allows developers to craft visually engaging applications that stand out in today's competitive market.

6. Built-In Animation

Creating interactive and engaging animations is a breeze with JavaFX. It offers built-in animation support, enabling developers to add motion and visual appeal to their applications without the complexities of external animation libraries.

7. Webview Integration

JavaFX seamlessly integrates web content into applications through its WebView component. This feature is particularly useful for embedding web pages or web-based content within your JavaFX application, expanding its capabilities.

8. Hardware Acceleration

JavaFX harnesses the power of hardware acceleration to optimize the performance of graphics-intensive applications. This results in smoother animations and an overall enhanced user experience.

9. Extensive Documentation

JavaFX boasts a wealth of documentation and a robust community of developers. This means that if you ever run into issues or need guidance, you can easily find the support and resources necessary to overcome any obstacles.

10. Active Development

Oracle actively maintains and develops JavaFX, ensuring that it remains up-to-date and continues to evolve with the changing landscape of technology. This commitment to improvement makes JavaFX a reliable choice for long-term development projects.

In conclusion, JavaFX is a powerhouse in the world of software development. Its feature-rich environment, cross-platform compatibility, and user-friendly tools make it an ideal choice for developers aiming to create exceptional applications. Whether you are developing a business application, a game, or a multimedia-rich project, JavaFX has the capabilities to bring your vision to life. Embrace the possibilities of JavaFX and unlock the potential for creating groundbreaking software applications.

Friday, December 30, 2022

JavaFX - Overview

JavaFX - Overview, Oracle Java Exam, Oracle Java Prep, Oracle Java Tutorial and Materials, Oracle Java Career, Java Skills, Java Job

Rich Internet Applications are those web applications which provide similar features and experience as that of desktop applications. They offer a better visual experience when compared to the normal web applications to the users. These applications are delivered as browser plug-ins or as a virtual machine and are used to transform traditional static applications into more enhanced, fluid, animated and engaging applications.

Unlike traditional desktop applications, RIA’s don’t require to have any additional software to run. As an alternative, you should install software such as ActiveX, Java, Flash, depending on the Application.

In an RIA, the graphical presentation is handled on the client side, as it has a plugin that provides support for rich graphics. In a nutshell, data manipulation in an RIA is carried out on the server side, while related object manipulation is carried out on the client side.

We have three main technologies using which we can develop an RIA. These include the following −

◉ Adobe Flash
◉ Microsoft Silverlight
◉ JavaFX

Adobe Flash

This software platform is developed by Adobe Systems and is used in creating Rich Internet Applications. Along with these, you can also build other Applications such as Vector, Animation, Browser Games, Desktop Applications, Mobile Applications and Games, etc.

This is the most commonly used platform for developing and executing RIA’s with a desktop browser penetration rate of 96%.

Microsoft Silverlight

Just like Adobe flash, Microsoft Silverlight is also a software application framework for developing as well as executing Rich Internet Applications. Initially this framework was used for streaming media. The present versions support multimedia, graphics, and animation as well.

This platform is rarely used with a desktop browser penetration rate of 66%.

JavaFX

JavaFX is a Java library using which you can develop Rich Internet Applications. By using Java technology, these applications have a browser penetration rate of 76%.

What is JavaFX?


JavaFX is a Java library used to build Rich Internet Applications. The applications written using this library can run consistently across multiple platforms. The applications developed using JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc.

To develop GUI Applications using Java programming language, the programmers rely on libraries such as Advanced Windowing Toolkit and Swing. After the advent of JavaFX, these Java programmers can now develop GUI applications effectively with rich content.

Need for JavaFX


To develop Client Side Applications with rich features, the programmers used to depend on various libraries to add features such as Media, UI controls, Web, 2D and 3D, etc. JavaFX includes all these features in a single library. In addition to these, the developers can also access the existing features of a Java library such as Swing.

JavaFX provides a rich set of graphics and media API’s and it leverages the modern Graphical Processing Unit through hardware accelerated graphics. JavaFX also provides interfaces using which developers can combine graphics animation and UI control.

One can use JavaFX with JVM based technologies such as Java, Groovy and JRuby. If developers opt for JavaFX, there is no need to learn additional technologies, as prior knowledge of any of the above-mentioned technologies will be good enough to develop RIA’s using JavaFX.

Features of JavaFX


Following are some of the important features of JavaFX −

◉ Written in Java − The JavaFX library is written in Java and is available for the languages that can be executed on a JVM, which include − Java, Groovy and JRuby. These JavaFX applications are also platform independent.

◉ FXML − JavaFX features a language known as FXML, which is a HTML like declarative markup language. The sole purpose of this language is to define a user Interface.

◉ Scene Builder − JavaFX provides an application named Scene Builder. On integrating this application in IDE’s such as Eclipse and NetBeans, the users can access a drag and drop design interface, which is used to develop FXML applications (just like Swing Drag & Drop and DreamWeaver Applications).

◉ Swing Interoperability − In a JavaFX application, you can embed Swing content using the Swing Node class. Similarly, you can update the existing Swing applications with JavaFX features like embedded web content and rich graphics media.

◉ Built-in UI controls − JavaFX library caters UI controls using which we can develop a full-featured application.

◉ CSS like Styling − JavaFX provides a CSS like styling. By using this, you can improve the design of your application with a simple knowledge of CSS.

◉ Canvas and Printing API − JavaFX provides Canvas, an immediate mode style of rendering API. Within the package javafx.scene.canvas it holds a set of classes for canvas, using which we can draw directly within an area of the JavaFX scene. JavaFX also provides classes for Printing purposes in the package javafx.print.

◉ Rich set of API’s − JavaFX library provides a rich set of API’s to develop GUI applications, 2D and 3D graphics, etc. This set of API’s also includes capabilities of Java platform. Therefore, using this API, you can access the features of Java languages such as Generics, Annotations, Multithreading, and Lambda Expressions. The traditional Java Collections library was enhanced and concepts like observable lists and maps were included in it. Using these, the users can observe the changes in the data models.

◉ Integrated Graphics library − JavaFX provides classes for 2d and 3d graphics.

◉ Graphics pipeline − JavaFX supports graphics based on the Hardware-accelerated graphics pipeline known as Prism. When used with a supported Graphic Card or GPU it offers smooth graphics. In case the system does not support graphic card then prism defaults to the software rendering stack.

History of JavaFX


JavaFX was originally developed by Chris Oliver, when he was working for a company named See Beyond Technology Corporation, which was later acquired by Sun Microsystems in the year 2005.

The following points give us more information of this project −

◉ Initially this project was named as F3 (Form Follows Functions) and it was developed with an intention to provide richer interfaces for developing GUI Applications.

◉ Sun Microsystems acquired the See Beyond company in June 2005, it adapted the F3 project as JavaFX.

◉ In the year 2007, JavaFX was announced officially at Java One, a world wide web conference which is held yearly.

◉ In the year 2008, Net Beans integrated with JavaFX was available. In the same year, the Java Standard Development Kit for JavaFX 1.0 was released.

◉ In the year 2009, Oracle Corporation acquired Sun Microsystems and in the same year the next version of JavaFX (1.2) was released as well.

◉ In the year 2010, JavaFX 1.3 came out and in the year 2011 JavaFX 2.0 was released.

◉ The latest version, JavaFX8, was released as an integral part of Java on 18th of March 2014.

Source: tutorialspoint.com

Saturday, June 27, 2020

JavaFX - Transformations

Transformation means changing some graphics into something else by applying rules. We can have various types of transformations such as Translation, Scaling Up or Down, Rotation, Shearing, etc.

Using JavaFX, you can apply transformations on nodes such as rotation, scaling and translation. All these transformations are represented by various classes and these belong to the package javafx.scene.transform.

S.No Transformation & Description 
1 Rotation

In rotation, we rotate the object at a particular angle θ (theta) from its origin. 
Scaling

To change the size of an object, scaling transformation is used. 
Translation

Moves an object to a different position on the screen. 
Shearing

A transformation that slants the shape of an object is called the Shear Transformation. 

Multiple Transformations


You can also apply multiple transformations on nodes in JavaFX. The following program is an example which performs Rotation, Scaling and Translation transformations on a rectangle simultaneously.

Save this code in a file with the name −

MultipleTransformationsExample.java.

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Rectangle; 
import javafx.scene.transform.Rotate; 
import javafx.scene.transform.Scale; 
import javafx.scene.transform.Translate; 
import javafx.stage.Stage; 
         
public class MultipleTransformationsExample extends Application { 
   @Override 
   public void start(Stage stage) { 
      //Drawing a Rectangle
      Rectangle rectangle = new Rectangle(50, 50, 100, 75); 
      
      //Setting the color of the rectangle 
      rectangle.setFill(Color.BURLYWOOD); 
      
      //Setting the stroke color of the rectangle 
      rectangle.setStroke(Color.BLACK); 
       
      //creating the rotation transformation 
      Rotate rotate = new Rotate(); 
      
      //Setting the angle for the rotation 
      rotate.setAngle(20); 
      
      //Setting pivot points for the rotation 
      rotate.setPivotX(150); 
      rotate.setPivotY(225); 
       
      //Creating the scale transformation 
      Scale scale = new Scale(); 
      
      //Setting the dimensions for the transformation 
      scale.setX(1.5); 
      scale.setY(1.5); 
      
      //Setting the pivot point for the transformation 
      scale.setPivotX(300); 
      scale.setPivotY(135); 
       
      //Creating the translation transformation 
      Translate translate = new Translate();       
      
      //Setting the X,Y,Z coordinates to apply the translation 
      translate.setX(250); 
      translate.setY(0); 
      translate.setZ(0); 
       
      //Adding all the transformations to the rectangle 
      rectangle.getTransforms().addAll(rotate, scale, translate); 
        
      //Creating a Group object  
      Group root = new Group(rectangle); 
      
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Multiple transformations"); 
         
      //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 MultipleTransformationsExample.java 
java MultipleTransformationsExample

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

JavaFX Transformations, Oracle Java Tutorial and Material, Java Exam Prep, Java Certification, Oracle Java Study Material

Transformations on 3D Objects


You can also apply transformations on 3D objects. Following is an example which rotates and translates a 3-Dimensional box.

Save this code in a file with the name RotationExample3D.java.

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.shape.Box; 
import javafx.scene.transform.Rotate; 
import javafx.scene.transform.Translate; 
import javafx.stage.Stage; 
         
public class RotationExample3D extends Application { 
   @Override 
   public void start(Stage stage) { 
      //Drawing a Box 
      Box box = new Box();  
      
      //Setting the properties of the Box 
      box.setWidth(150.0); 
      box.setHeight(150.0);   
      box.setDepth(150.0);       
       
      //Creating the translation transformation 
      Translate translate = new Translate();       
      translate.setX(400); 
      translate.setY(150); 
      translate.setZ(25);  
       
      Rotate rxBox = new Rotate(0, 0, 0, 0, Rotate.X_AXIS); 
      Rotate ryBox = new Rotate(0, 0, 0, 0, Rotate.Y_AXIS); 
      Rotate rzBox = new Rotate(0, 0, 0, 0, Rotate.Z_AXIS); 
      rxBox.setAngle(30); 
      ryBox.setAngle(50); 
      rzBox.setAngle(30); 
      box.getTransforms().addAll(translate,rxBox, ryBox, rzBox); 
        
      //Creating a Group object  
      Group root = new Group(box); 
         
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Drawing a cylinder"); 
         
      //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 RotationExample3D.java 
java RotationExample3D 

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

JavaFX Transformations, Oracle Java Tutorial and Material, Java Exam Prep, Java Certification, Oracle Java Study Material

Wednesday, June 24, 2020

JavaFX - Application

We will discuss the structure of a JavaFX application in detail and also learn to create a JavaFX application with an example.

JavaFX Application Structure


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

JavaFX Application, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Certification

Stage

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.

Scene

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.

Scene Graph and Nodes

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.

◉ 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 earlier 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 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.

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

Creating a JavaFX Application


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.

Application Class

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

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

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.

JavaFX Application, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Certification

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

◉ 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 application"); 
       
//Setting the scene to Stage 
primaryStage.setScene(scene); 
       
//Displaying the stage 
primaryStage.show();

Lifecycle of JavaFX Application


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.

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

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.

◉ Init() method is called.

◉ The start() method is called.

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

Terminating the JavaFX Application

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

Example 1 – Creating an Empty Window


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

Step 1: Creating a Class

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 {      
   }    

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

primaryStage.setTitle("Sample Application");

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

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.

JavaFX Application, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Certification

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 line using the JavaFX library.

Following are the steps −

Step 1: Creating a Class

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 {     
   }    

Step 2: Creating a Line

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

Step 3: Setting Properties to the 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);

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

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

primaryStage.setTitle("Sample Application");

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

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.

JavaFX Application, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Certification

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 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 {     
   } 
}

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

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

primaryStage.setTitle("Sample Application");

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

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 OracleJavaCertified"); 
         
      //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.

Welcome to OracleJavaCertified

Friday, June 19, 2020

JavaFX - Architecture

JavaFX provides a complete API with a rich set of classes and interfaces to build GUI applications with rich graphics. The important packages of this API are −

◉ javafx.animation − Contains classes to add transition based animations such as fill, fade, rotate, scale and translation, to the JavaFX nodes.

◉ javafx.application − Contains a set of classes responsible for the JavaFX application life cycle.

◉ javafx.css − Contains classes to add CSS–like styling to JavaFX GUI applications.

◉ javafx.event − Contains classes and interfaces to deliver and handle JavaFX events.

◉ javafx.geometry − Contains classes to define 2D objects and perform operations on them.

◉ javafx.stage − This package holds the top level container classes for JavaFX application.

◉ javafx.scene − This package provides classes and interfaces to support the scene graph. In addition, it also provides sub-packages such as canvas, chart, control, effect, image, input, layout, media, paint, shape, text, transform, web, etc. There are several components that support this rich API of JavaFX.

The following illustration shows the architecture of JavaFX API. Here you can see the components that support JavaFX API.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learning

Scene Graph


In JavaFX, the GUI Applications were coded using a Scene Graph. A Scene Graph is the starting point of the construction of the GUI Application. It holds the (GUI) application primitives that are termed as nodes.

A node is a visual/graphical object and it 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.

In general, a collection of nodes makes a scene graph. All these nodes are arranged in a hierarchical order as shown below.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Learning

Each node in the scene graph has a single parent, and the node which does not contain any parents is known as the root node.

In the same way, every node has one or more children, and the node without children is termed as leaf node; a node with children is termed as a branch node.

A node instance can be added to a scene graph only once. The nodes of a scene graph can have Effects, Opacity, Transforms, Event Handlers, Event Handlers, Application Specific States.

Prism


Prism is a high performance hardware–accelerated graphical pipeline that is used to render the graphics in JavaFX. It can render both 2-D and 3-D graphics.

To render graphics, a Prism uses −

◉ DirectX 9 on Windows XP and Vista.
◉ DirectX 11 on Windows 7.
◉ OpenGL on Mac and Linux, Embedded Systems.

In case the hardware support for graphics on the system is not sufficient, then Prism uses the software render path to process the graphics.

When used with a supported Graphic Card or GPU, it offers smoother graphics. Just in case the system does not support a graphic card, then Prism defaults to the software rendering stack (either of the above two).

GWT (Glass Windowing Toolkit)


As the name suggests, GWT provides services to manage Windows, Timers, Surfaces and Event Queues. GWT connects the JavaFX Platform to the Native Operating System.

Quantum Toolkit


It is an abstraction over the low-level components of Prism, Glass, Media Engine, and Web Engine. It ties Prism and GWT together and makes them available to JavaFX.

WebView


Using JavaFX, you can also embed HTML content in to a scene graph. WebView is the component of JavaFX which is used to process this content. It uses a technology called Web Kit, which is an internal open-source web browser engine. This component supports different web technologies like HTML5, CSS, JavaScript, DOM and SVG.

Using WebView, you can −

◉ Render HTML content from local or remote URL.
◉ Support history and provide Back and Forward navigation.
◉ Reload the content.
◉ Apply effects to the web component.
◉ Edit the HTML content.
◉ Execute JavaScript commands.
◉ Handle events.

In general, using WebView, you can control web content from Java.

Media Engine


The JavaFX media engine is based on an open-source engine known as a Streamer. This media engine supports the playback of video and audio content.

The JavaFX media engine provides support for audio for the following file formats −

Audio - MP3
- WAV
- AIFF 
Video  - FLV 

The package javafx.scene.media contains the classes and interfaces to provide media functionality in JavaFX. It is provided in the form of three components, which are −

◉ Media Object − This represents a media file

◉ Media Player − To play media content.

◉ Media View − To display media.