JavaFX: Modern GUI Development
JavaFX: Modern GUI Development
JavaFX is a software platform and a set of graphics and media packages for creating rich,
interactive, and cross platform graphical user interfaces (GUIs). Developed by Oracle, JavaFX is
designed to replace the aging Swing GUI toolkit in Java applications. It provides a modern and
versatile framework for building desktop, mobile, and web applications with a focus on visually
appealing user interfaces and multimedia support.
JavaFX is a Java library and a GUI toolkit designed to develop and facilitate Rich Internet
applications, web applications, and desktop applications. The most significant perk of using
JavaFX is that the applications written using this library can run on multiple operating systems
like Windows, Linux, iOS, Android, and several platforms like Desktops, Web, Mobile Phones,
TVs, Tablets, etc. This characteristic of the JavaFX library makes it very versatile across
operating systems and different platforms.
Sun Microsystems (now acquired by Oracle Corporation) released a toolkit known as JavaFX to
promote desktop and rich internet applications (RIA) that can be accessed from the category of
devices. After the arrival of JavaFX, Java developers and programmers were able to develop the
GUI applications more effectively and more productively.
Note: Rich Internet Applications are those web applications that allow alike characteristics and
expertise as that of desktop applications. These applications contribute more satisfying visual
experience to the users when compared to the standard web applications.
JavaFX was introduced to supersede the Java Swing GUI framework. Nevertheless, the JavaFX
provides more enhanced functionalities and features than the Java Swing. Similar to the Java
Swing, the JavaFX also implements its own components. The components of the JavaFX are
irrespective of the Operating system. JavaFX is considered to be lightweight and hardware
stimulated. According to a report, after using the JavaFX for the development of Rich Internet
applications (RIA), the browser penetration rate recorded for these applications was 76%.
Need of JavaFX
Programmers and developers used to require several libraries for adding various
functionalities like media, UI controls, animations and effects, 2D and 3D shapes, etc., in
their applications.
JavaFX also displays a valuable collection of graphics and various media APIs, which
can further help in designing smooth applications.
JavaFX also leverages the improved Graphical Processing Unit (GUI) with the help of
hardware-accelerated graphics.
Scene Graph: JavaFX uses a scene graph to represent the graphical user interface. The scene
graph is a hierarchical tree structure of visual elements (nodes), allowing for efficient rendering
and manipulation of the user interface.
CSS Styling: JavaFX supports Cascading Style Sheets (CSS), enabling developers to apply
styles to UI components for consistent and visually appealing designs. This makes it easier to
separate the presentation from the logic of the application.
FXML: JavaFX provides FXML, an XML based language for designing user interfaces. FXML
allows developers to define the structure of UI layouts in a declarative manner, separating the
design from the application logic.
Rich Set of UI Controls: JavaFX includes a wide variety of UI controls (buttons, text fields,
tables, etc.) and layout managers to facilitate the construction of complex and responsive user
interfaces.
Graphics and Multimedia Support: JavaFX supports 2D and 3D graphics rendering, as well as
multimedia features such as audio and video playback. This makes it suitable for applications
that require advanced graphical capabilities.
Animation API: JavaFX provides a robust Animation API that allows developers to create
smooth and visually appealing animations, enhancing the user experience.
Integration with Java: JavaFX seamlessly integrates with the Java programming language,
making it easy for Java developers to adopt and use it for building modern GUI applications.
Java Library – JavaFX is a Java library, which allows the user to gain the support of all the Java
characteristics such as multithreading, generics, lambda expressions, and many more. The user
can also use any of the Java editors or IDE’s of their choice, such as Eclipse, NetBeans, to write,
compile, run, debug, and package their JavaFX application.
Platform Independent – The rich internet applications made using JavaFX are platform-
independent. The JavaFX library is open for all the scripting languages that can be administered
on a JVM, which comprise – Java, Groovy, Scala, and JRuby.
WebView – JavaFX applications can also insert web pages. To embed web pages, Web View of
JavaFX uses a new HTML rendering engine technology known as WebKitHTML. WebView is
used to make it possible to insert web pages within a JavaFX application. JavaScript running in
WebView can call Java APIs and vice-versa.
High-Performance media engine – Like the graphics pipeline, JavaFX also possesses a media
pipeline that advances stable internet multimedia playback at low latency. This high-performance
media engine or media pipeline is based on a multimedia framework known as Gstreamer.
JavaFX has numerous built-in elements that are interconnected with each other. JavaFX library
comprises a valuable collection of APIs, classes, and interfaces that are more than sufficient to
produce rich internet applications and GUI applications with intense graphics that can run
consistently over multiple platforms.
The subsequent figure displays the complete architecture of the JavaFX platform.
As we can see in the above figure that, JavaFX architecture comprises many different
components. These components are briefly described as follows:
1. JavaFX API – The topmost layer of JavaFX architecture holds a JavaFX public API that
implements all the required classes that are capable of producing a full-featured JavaFX
application with rich graphics. The list of all the important packages of this API is as
follows.
2. Scene Graph – A Scene Graph is the starting point of the development of any of the GUI
Applications. In JavaFX, all the GUI Applications are made using a Scene Graph only.
The Scene Graph includes the primitives of the rich internet applications that are known
as nodes. In simple words, a single component in a scene graph is known as a node. In
general, a scene graph is made up of a collection of nodes. All these nodes are organized
in the form of a hierarchical tree that describes all of the visual components of the
application’s user interface (UI). A node instance can be appended to a scene graph only
once. The nodes of a scene graph can have numerous segments like Effects, Opacity,
Transforms, Event Handlers, Application Specific States. The nodes are of three general
types.
Root Node – A root node is a node that does not have any node as its parent.
Leaf Node – A leaf node is a node that does not contain any node as its children.
Branch Node – A branch node is a node that contains a node as its parent and also has a
node as its children.
3. Quantum Toolkit – Quantum Toolkit is used to connect prism and glass windowing
tool kits collectively and makes them prepared for the above layers in the stack. In simple
words, it ties Prism and GWT together and makes them available to JavaFX.
4. Prism – The graphics of the JavaFX applications are based on the hardware-accelerated
graphics rendering pipeline, commonly known as Prism. The Prism engine supports
smooth JavaFX graphics that can be executed swiftly when utilized with a backed
graphics card or graphics processing unit (GPU). In the situation where the system does
not contain the graphic cards, then the prism engine defaults to the software rendering
stack. To interpret graphics, a Prism practice:
DirectX 9 on Windows XP and Vista.
DirectX 11 on Windows 7.
OpenGL on Mac and Linux, Embedded Systems.
5. Glass Windowing Toolkit – Glass Windowing Toolkit or simply Glass is a platform-
dependent layer that assists in connecting the JavaFX platform to the primary operating
system (OS). Glass Windowing Toolkit is very useful as it provides services such as
controlling the windows, events, timers, and surfaces to the native operating system.
6. WebView – JavaFX applications can also insert web pages. To embed web pages, Web
View of JavaFX uses a new HTML rendering engine technology known as
WebKitHTML. WebView is used to make it possible to insert web pages within a
JavaFX application. JavaScript appearing in WebView can call Java APIs and vice-versa.
This element promotes different web technologies like HTML5, CSS, JavaScript, DOM,
and SVG. Using web view, we can execute the HTML content from the JavaFX
application and can also implement some CSS styles to the user interface (UI) part of the
application.
7. Media Engine – Like the graphics pipeline, JavaFX also possesses a media pipeline that
advances stable internet multimedia playback at low latency. This high-performance
media engine or media pipeline is based on a multimedia framework known as
Gstreamer. By applying the Media engine, the JavaFX application can support the
playback of audio and video media files. The package javafx.scene.media covers all the
classes and interfaces that can provide media functionalities to JavaFX applications
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
primaryStage.setScene (scene);
primaryStage.show();
launch(args);
}
1.2. JAVAFX layout components
3. GridPane
Organizes its children in a grid, using rows and columns.
Enables precise control over the placement of UI elements.
Example:
4. BorderPane:
Divides the layout into five regions: top, bottom, left, right, and center.
Suitable for creating a typical page layout.
Example:
borderPane.setTop(new MenuBar());
5. StackPane:
Stacks its children on top of each other, with the last child added appearing on
top.
Useful for overlaying elements.
Example:
6. FlowPane:
Places its children in a flow, wrapping to the next row or column when space
is limited.
Useful for responsive UIs.
Example:
7. AnchorPane:
Positions its children based on absolute coordinates or relative to other
children.
Provides finegrained control over element placement.
Example:
JavaFX provides a set of fundamental UI controls that serve as building blocks for creating
interactive and userfriendly graphical interfaces. These controls are essential for capturing user
input and presenting information.
These basic UI controls can be customized, styled, and combined to create more complex user
interfaces. Additionally, event handling mechanisms can be implemented to respond to user
interactions, making applications dynamic and responsive.
Let's explore some of the basic UI controls and how to use them:
Button: Represents a clickable button that triggers an action when pressed.
Example:
ComboBox: Presents a dropdown list of items from which the user can select one.
Example:
Slider: Allows users to select a value within a specified range by dragging a thumb.
Event handlers in JavaFX allow you to respond to user actions and interactions with UI controls.
They enhance the functionality of your application by executing specific code when events
occur. Here's an example of attaching an event handler to a button:
Example:
myButton.setOnAction(e > {
System.out.println("Button clicked!");
});
1.3.2. UI controls
In JavaFX, UI controls are the building blocks of graphical user interfaces, enabling developers
to create interactive and userfriendly applications. Manipulating UI controls involves
customizing their properties, handling events, and dynamically updating their states. Let's
explore key concepts related to UI controls:
Customizing Properties:
UI controls have various properties that define their appearance and behavior.
Example: Customizing the text of a button.
myButton.setText("New Label");
Handling Events:
myButton.setOnAction(e > {
System.out.println("Button clicked!");
});
myLabel.setText("Updated Text");
Visibility:
myCheckBox.setVisible(false);
Tool Tips:
Context Menus
myTextField.setContextMenu(contextMenu);
Keyboard Shortcuts:
myButton.setMnemonicParsing(true);
Composite UI controls in JavaFX allow developers to create more complex and reusable
components by combining multiple basic UI controls. This enables the construction of
sophisticated user interfaces with enhanced functionality. Let's explore the concept of composite
UI controls and their implementation:
Composite controls are created by combining multiple basic UI controls within a single
container.
Example: Creating a composite control with a label, text field, and button.
public CustomCompositeControl() {
Composite controls can have their own methods, properties, and event handlers.
Example: Adding a method to set the label text dynamically.
titleLabel.setText(text);
actionButton.setOnAction(e > {
});
Reusability:
1.4. Shapes
In the context of JavaFX or graphics programming in general, "shapes" refer to basic geometric
entities that can be drawn on a canvas or a graphical user interface. JavaFX provides various
classes for creating and manipulating shapes, allowing developers to incorporate visual elements
into their applications.
Shapes are fundamental for creating graphical elements in user interfaces, visualizations, games,
and other applications where drawing and rendering play a crucial role. They provide a versatile
and powerful means of incorporating visual elements into JavaFX applications.
A. Color:
Palette of Colors:
JavaFX offers a wide palette of colors through the “Color” class.
Example: Using predefined colors.
rectangle.setFill(Color.GREEN);
rectangle.setStroke(Color.BLACK);
Custom Colors:
Custom colors can be created using RGB or RGBA values.
Example:
B. Texts
Text Rendering:
JavaFX allows the rendering of text using the “Text” class.
Example: Displaying text on the screen.
Font Manipulation:
Fonts in JavaFX can be customized using the “Font” class.
Example: Setting the font size and style.
Styling Text:
Text can be styled using CSS like styling options.
Example: Applying styling to text.
Text Alignment:
Text alignment properties control how text is positioned within its layout bounds.
Example:
text.setTextAlignment(TextAlignment.CENTER);
Font Selection:
Fonts in JavaFX are represented by the Font class, allowing the specification of
font family, style, and size.
Example:
Font customFont = Font.font("Times New Roman",
FontWeight.NORMAL, FontPosture.ITALIC, 16);
Applying Fonts:
Fonts can be applied to text nodes to customize their appearance.
Example:
text.setFont(customFont);
Dynamic Font Size:
Font size can be dynamically adjusted based on application logic.
Example:
A. Lines
Creating Lines:
Lines in JavaFX are represented by the “Line” class.
Example: Drawing a line.
line.setStrokeWidth(2);
line.setStroke(Color.BLACK);
B. Circle
Creating Circles
Circles can be created using the “Circle” class.
Example: Generating a circle.
Circle circle = new Circle(50, Color.BLUE);
circle.setCenterX(100);
circle.setCenterY(100);
C. Rectangle
Creating Rectangles
Rectangles are represented by the “Rectangle” class.
Example: Constructing a rectangle.
Rectangle rectangle = new Rectangle(100, 50);
Properties and Positioning:
Rectangles have properties like width, height, and color.
Example: Setting rectangle properties.
rectangle.setX(50);
rectangle.setY(50);
Dynamic Updates:
Properties of shapes can be dynamically updated to create interactive interfaces.
Example: Dynamically changing the position of a rectangle
rectangle.setX(150);
1. Properties in JavaFX: Properties represent the state of UI components and can be observed
for changes. Example: A property representing the text of a label.
Binding Properties: Properties can be bound together, ensuring that changes in one property
are reflected in another. Example: Binding the text property of a label to a text field.
label.textProperty().bind(textField.textProperty());
widthProperty.bindBidirectional(heightProperty);
Conditional Binding: Bindings can have conditions, triggering updates based on specified
criteria.
label.textFillProperty().bind(Bindings.when(condition).then(Color.RED).otherwise
(Color.GREEN));
1. Graphics in JavaFX:
Canvas and GraphicsContext: The “Canvas” class provides an area for drawing, and
“GraphicsContext” allows rendering shapes, text, and images. Example: Drawing a circle on a
canvas.
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLUE);
Image Rendering: JavaFX supports loading and displaying images. Example: Loading and
displaying an image.
2. Animation in JavaFX:
Animation API: JavaFX provides the “Animation” class and its subclasses for creating
animations.
fadeTransition.setFromValue(0.0);
fadeTransition.setToValue(1.0);
fadeTransition.play();
);
translateTransition.play();
Handling Animation Events: Animation events, such as onfinish events, can be handled to
trigger actions. Example: Adding an event handler to an animation.
translateTransition.setToX(200);
translateTransition.play();