[Go to site: main page, start]

0% found this document useful (0 votes)
45 views11 pages

JavaFX Tutorial for Beginners and Pros

Java FX document

Uploaded by

Sanjay Sahoo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views11 pages

JavaFX Tutorial for Beginners and Pros

Java FX document

Uploaded by

Sanjay Sahoo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaFX

JavaFX tutorial provides basic and advanced concepts of JavaFX.


Our JavaFX tutorial is designed for beginners and professionals.
JavaFX is a Java library that is used to develop Desktop
applications as well as Rich Internet Applications (RIA). The
applications built in JavaFX, can run on multiple platforms
including Web, Mobile and Desktops.
Our JavaFX tutorial includes all topics of JavaFX library such as
Fundamentals, 2D Shapes, 3D Shapes, Effects, Animation, Text,
Layouts, UI Controls, Transformations, Charts, JavaFX with CSS,
JavaFX with Media etc.
What is JavaFX?
JavaFX is intended to replace swing in Java applications as a GUI
framework. However, It provides more functionalities than
swing. Like Swing, JavaFX also provides its own components and
doesn't depend upon the operating system. It is lightweight and
hardware accelerated. It supports various operating systems
including Windows, Linux and Mac OS.
Features of JavaFX

Feature Description

Java Library It is a Java library which consists of


many classes and interfaces that are
written in Java.

FXML FXML is the XML based Declarative


mark up language. The coding can be
done in FXML to provide the more
enhanced GUI to the user.
Scene Builder Scene Builder generates FXML mark-
up which can be ported to an IDE.

Web view Web pages can be embedded with


JavaFX applications. Web View uses
WebKitHTML technology to embed
web pages.

Built in UI controls JavaFX contains Built-in components


which are not dependent on operating
system. The UI component are just
enough to develop a full featured
application.

CSS like styling JavaFX code can be embedded with


the CSS to improve the style of the
application. We can enhance the view
of our application with the simple
knowledge of CSS.

Swing The JavaFX applications can be


interoperability embedded with swing code using the
Swing Node class. We can update the
existing swing application with the
powerful features of JavaFX.

Canvas API Canvas API provides the methods for


drawing directly in an area of a
JavaFX scene.

Rich Set of APIs JavaFX provides a rich set of API's to


develop GUI applications.
Integrated An integrated set of classes are
Graphics Library provided to deal with 2D and 3D
graphics.

Graphics Pipeline JavaFX graphics are based on


Graphics rendered pipeline(prism). It
offers smooth graphics which are
hardware accelerated.

High Performance The media pipeline supports the


Media Engine playback of web multimedia on a low
latency. It is based on a Gstreamer
Multimedia framework.

Self-contained Self Contained application packages


application have all of the application resources
deployment model and a private copy of Java and JavaFX
Runtime.

javaFX Application Structure


JavaFX application is divided hierarchically into three main
components known as Stage, Scene and nodes. We need to
import [Link] class in every JavaFX
application. This provides the following life cycle methods for
JavaFX application.
o public void init()
o public abstract void start(Stage primaryStage)
o public void stop()
in order to create a basic JavaFX application, we need to:
1. Import [Link] into our code.
2. Inherit Application into our class.
3. Override start() method of Application class.
Stage
Stage in a JavaFX application is similar to the Frame in a Swing
Application. It acts like a container for all the JavaFX objects.
Primary Stage is created internally by the platform. Other stages
can further be created by the application. The object of primary
stage is passed to start method. We need to call show method on
the primary stage object in order to show our primary stage.
Initially, the primary Stage looks like following.

However, we can add various objects to this primary stage. The


objects can only be added in a hierarchical way i.e. first, scene
graph will be added to this primaryStage and then that scene
graph may contain the nodes. A node may be any object of the
user's interface like text area, buttons, shapes, media, etc.
Scene
Scene actually holds all the physical contents (nodes) of a JavaFX
application. [Link] class provides all the methods to
deal with a scene object. Creating scene is necessary in order to
visualize the contents on the stage.
At one instance, the scene object can only be added to one stage.
In order to implement Scene in our JavaFX application, we must
import [Link] package in our code. The Scene can be
created by creating the Scene class object and passing the layout
object into the Scene class constructor. We will discuss Scene class
and its method later in detail.
Scene Graph
Scene Graph exists at the lowest level of the hierarchy. It can be
seen as the collection of various nodes. A node is the element
which is visualized on the stage. It can be any button, text box,
layout, image, radio button, check box, etc.
The nodes are implemented in a tree kind of structure. There is
always one root in the scene graph. This will act as a parent node
for all the other nodes present in the scene graph. However, this
node may be any of the layouts available in the JavaFX system.
The leaf nodes exist at the lowest level in the tree hierarchy. Each
of the node present in the scene graphs represents classes
of [Link] package therefore we need to import the package
into our application in order to create a full featured javafx
application.
JavaFX Key Features
JavaFX's key features include:
1. From JavaFX 2.0, JavaFX is written in Java (no need to learn a
new language). Starting from JDK 8, JavaFX is part of JDK.
2. Support CSS for skinning.
3. Support FXML: a XML-based declarative language to define
the structure of the user interface separated from the
application code.
4. Swing interoperability: You can use Swing UI in JavaFX
application.
5. WebView: for embedding HTML contents.
6. 2D/3D Graphics
7. Media: audio (mp3, wav, aiff), video (flv) and image.
8. Provide a JavaScript engine.
9. ......
In this article, I assume that you have some knowledge in Swing,
such as container/component, event-handling, and layout.
1. JavaFX By Examples

JavaFX is huge, with 36 packages. These are the commonly-used


packages:
 [Link]: JavaFX application
 [Link]: top-level container
 [Link]: scene and scene graph.
 [Link].*: control, layout, shape, etc.
 [Link]: event handling
 [Link]: animation
1.1 Example 1: Hello World

1import [Link];
2import [Link];
3import [Link];
4import [Link];
5import [Link];
6import [Link];
7import [Link];
8
9public class JavaFXHello extends Application {
10 private Button btnHello; // Declare a "Button" control
11
12 @Override
13 public void start(Stage primaryStage) {
14 // Construct the "Button" and attach an "EventHandler"
15 btnHello = new Button();
16 [Link]("Say Hello");
17 // Using JDK 8 Lambda Expression to construct an EventHandler<A
18 [Link](evt -> [Link]("Hello World!"));
19
20 // Construct a scene graph of nodes
21 StackPane root = new StackPane(); // The root of scene graph is a la
22 [Link]().add(btnHello); // The root node adds Button as a
23
24 Scene scene = new Scene(root, 300, 100); // Construct a scene given
25 [Link](scene); // The stage sets scene
26 [Link]("Hello"); // Set window's title
27 [Link](); // Set visible (show it)
28 }
29
30 public static void main(String[] args) {
31 launch(args);
32 }
33}
How It Works
1. A JavaFX GUI Program extends
from [Link] (just like a Java Swing
GUI program extends from [Link]).
2. JavaFX provides a huge set of controls (or components) in
package [Link],
including Label, Button and TextField.
3. We declare and construct a Button control, and attach
a [Link]<ActionEvent> to the Button, via
method setOnAction() (of ButtonBase superclass), which
takes an EventHandler<ActionEvent>, as follows:
public final void setOnAction(EventHandler<ActionEvent>
value)
The EventHandler is a Functional Interface with an abstract
method handle(), defined as follows:

package [Link];
@FunctionalInterface
public interface EventHandler<T extends Event> extends
EventListener {
void handle(T event); // public abstract
}
We can trigger the handle() by firing the button, via clicking
the button with the mouse or touch, key press, or invoke
the fire() method programmatically.
In this example, we use a one-liner Lambda Expression (JDK
8) to construct an instance of Functional
Interface EventHandler. You can also use an anonymous
inner class (Pre JDK 8), as follows:

[Link](new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent evt) {
[Link]("Hello World!");
}
});
4. JavaFX uses the metaphor of a theater to model the graphics
application. A stage (defined by the [Link] class)
represents the top-level container (window). The individual
controls (or components) are contained in a scene (defined by
the [Link] class). An application can have more
than one scenes, but only one of the scenes can be displayed
on the stage at any given time. The contents of a scene is
represented in a hierarchical scene graph of nodes (defined
by [Link]).

5. To construct the UI:


1. Prepare a scene graph.
2. Construct a scene, with the root node of the scene graph.
3. Setup the stage with the constructed scene.
6. In this example, the root node is a "layout" node (container)
named [Link], which layouts its
children in a back-to-front stack. This layout node has one
child node, which is the Button. To add child node(s) under a
layout, use:
7. [Link]().add(Node node) // Add one
node

[Link]().addAll(Node... nodes) // Add all


nodes
Notes: A JavaFX's Pane is similar to Swing's JPanel. However,
JavaFX has layout-specific Pane, such
as FlowPane, GridPane and BorderPane, which is similar to a
Swing's JPanel with FlowLayout, GridLayout and BorderLay
out.

8. We allocate a [Link] by specifying the root of the


scene graph, via constructor:

public Scene(Parent root, double width, double height)

where [Link] is a subclass of [Link],


which serves as the base class for all nodes that have children
in the scene graph.

9. We then set the stage's scene, title, and show it.

Common questions

Powered by AI

Unlike Swing applications, which organize components in containers directly, JavaFX uses a hierarchical scene graph model where visual nodes are organized in a graph-like structure. This scene graph starts with a single root node, which could be a layout node such as StackPane, and branches out to include all other UI components, similar to a tree. This model allows more efficient rendering and a cleaner separation of UI components than the more linear container-component hierarchy of Swing. JavaFX also supports more advanced features like 3D shapes and animations due to this structure .

JavaFX offers several unique advantages for multimedia handling, including a high-performance media engine supporting playback of audio and video with low latency. It supports a range of multimedia formats such as MP3, AIFF, and FLV, and uses a lightweight, hardware-accelerated graphics stack to ensure smooth playback. Additionally, JavaFX’s integration of the WebView component, which uses WebKit for rendering HTML content, enhances its multimedia capabilities by allowing rich web content embedding with reduced performance overhead .

The integration of WebView in JavaFX expands application capabilities by enabling embedded web content, bridging the gap between desktop and web environments. This feature allows developers to include live web pages, HTML content, and interact with web APIs directly within a native JavaFX application. It uses WebKit, offering modern web capabilities like CSS3, HTML5, and JavaScript. This integration is highly beneficial for applications requiring dynamic content updates, embedded web services, or interactive and rich-media experiences, which are traditionally beyond the scope of desktop applications .

The Canvas API in JavaFX provides developers with a powerful tool for custom rendering, allowing for the direct drawing of shapes, images, and custom graphics. Unlike standard UI components, the Canvas does not rely on pre-existing nodes but provides a drawing surface as part of a JavaFX scene, which can be manipulated using an accompanying GraphicsContext object. This enables more complex and custom visualizations that are not possible with standard UI components, such as detailed drawings or dynamic graphical modifications based on real-time data .

FXML allows developers to build the graphical user interface in a more modular and declarative manner, separating the UI layout from the business logic. This separation can facilitate collaboration among developers and designers, enable easier maintenance and modifications of the UI, and provide clearer visual context. Additionally, using Scene Builder with FXML can provide a visual design interface, which makes the process more intuitive and reduces the potential for coding errors in complex layouts .

JavaFX's interoperability with Swing is crucial for developers who need to integrate JavaFX components into existing Swing applications or gradually transition from Swing to JavaFX. This feature allows developers to leverage the advanced features of JavaFX, such as rich media integration and CSS styling, without rewriting entire applications. Scenarios where this might be critical include legacy applications that require modern updates, or projects where full migration is not feasible due to time constraints or budget limitations. Interoperability is facilitated through the use of the SwingNode class, which enables embedding JavaFX scenes in Swing applications .

In JavaFX, the Stage represents the main window of the application, similar to JFrame in Swing. It serves as the top-level container for all JavaFX components, holding the Scene graph which contains the application's UI elements. Unlike JFrame, Stage is specifically designed to integrate with the platform's native windowing system, potentially offering better performance and functionality such as transparency and non-rectangular shapes. The primary Stage is automatically created by the platform at startup, and additional Stages can be created for additional windows .

Lambda expressions in JavaFX enhance code efficiency and readability by enabling a more concise way to implement event handling. Instead of creating anonymous inner classes for event handling, developers can directly implement the functional interface with a single-line expression. This reduces boilerplate code and makes the code easier to read and maintain. In cases like registering EventHandler for a Button, a lambda expression can be used to succinctly define the action that should occur without the verbosity of traditional anonymous classes .

JavaFX natively supports a CSS-like styling language which allows for greater flexibility and control over the appearance of UI components, similar to web development. This differs from Swing, which relies primarily on LookAndFeel themes and requires more manual coding for custom styles. The CSS support in JavaFX can be used to define styles in a separate stylesheet, making it easy to change the appearance of an application without altering the code. This approach enables more dynamic and sophisticated styling options, such as transitions and animations, directly through the CSS .

The Scene Graph in JavaFX contributes to performance improvements by allowing the underlying rendering engine to optimize drawing and updating operations. This graph-based representation provides a structured and hierarchical way to organize and manage the nodes that make up the application's GUI, allowing the system to intelligently determine which parts of the UI need to be redrawn when changes occur. This leads to reduced overhead and more efficient use of resources, as only modified nodes are re-rendered, rather than the entire UI .

You might also like