0% found this document useful (0 votes)
16 views57 pages

JavaFX GUI Development Guide

Uploaded by

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

JavaFX GUI Development Guide

Uploaded by

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

Chapter three

Java GUI using JAVAFX


Outline
 JAVAFX architecture and Program structure
 JAVAFX layout components
 Basic UI controls
 Event handlers
 UI controls
 Composite UI controls
 Shapes
• Color, Texts, Fonts
• Lines, Circle, Rectangle
• CSS styling
• Properties and Bindings
• Graphics and Animation

12/3/2025 2
Introduction to java GUI
What is a GUI? Advantages of Java GUI
 GUI stands for Graphical User Interface.  Platform independent
 Event-driven programming model
 It allows users to interact with a program  Easy to build interactive applications
visually using components such as:  Customizable and extensible component
Buttons
Text fields Tools for GUI Development
 NetBeans IDE → Built-in GUI Builder (drag-
Labels and-drop for Swing/JavaFX)
Menus  Eclipse → Plugins available for GUI design
Windows  Scene Builder → Visual FXML designer for
JavaFX
 It replaces text-based (console)
interaction with a more user-friendly
interface.
Introduction to java GUI
Java provides several ways to create GUIs:

Framework Description Common Usage

AWT (Abstract Window The original Java GUI toolkit;


Simple, older apps
Toolkit) uses native OS components.

Built on AWT but provides


Swing richer, lightweight Most desktop apps
components.

Modern toolkit with support


Modern desktop and
JavaFX for multimedia, CSS styling,
educational projects
and FXML.
Introduction to java GUI
Swing – The Most Common
GUI Library import [Link].*;
Swing is part of Java’s [Link]
public class SimpleGUI {
package.
public static void main(String[] args) {
Common Swing components: JFrame frame = new JFrame("My First GUI"); // Create
•JFrame → Main window window
•JButton → Clickable button JButton button = new JButton("Click Me"); // Create
•JLabel → Display text button
•JTextField → Input text box
•JPanel → Container for other [Link](JFrame.EXIT_ON_CLOSE);
components [Link](300, 200);
[Link](button); // Add button to frame
[Link](true);
}
}
Introduction to java GUI

import [Link].*;
public class SimpleGUI {
public static void main(String[] args) {
JFrame frame = new JFrame("My First GUI"); // Create window
JButton button = new JButton("Click Me"); //Create button
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 200);
[Link](button); // Add button to frame
[Link](true);
}
}
Javafx architecture
• JavaFX is a software platform that allows developers to build various content-rich
client applications, which operate consistently across several platforms.
• It is a complete API with a rich set of classes and interfaces to build GUI
applications with rich graphics.
• Some of the important packages of this API are:
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]

12/3/2025 7
Cont…
• let us learn the architectural design of this JavaFX platform and how
its components are interconnected.

12/3/2025 8
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.

12/3/2025 9
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.
• 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).

12/3/2025 10
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.

12/3/2025 11
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.

• In general, using WebView, you can control web content from Java.
12/3/2025 12
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 − AudioMP3, WAV, AIFF and VideoFLV

• The package [Link] contains the classes and interfaces to


provide media functionality in JavaFX.

12/3/2025 13
Javafx program structure

A JavaFX application typically has the following structure:


[Link] JavaFX packages
[Link] the Application class
[Link] the start(Stage primaryStage) method
[Link] UI elements (Nodes)
[Link] up a Scene and add it to the Stage
[Link] the Stage

12/3/2025 14
Javafx program structure

A JavaFX application typically has the following structure:


[Link] JavaFX packages
[Link] the Application class
[Link] the start(Stage primaryStage) method
[Link] UI elements (Nodes)
[Link] up a Scene and add it to the Stage
[Link] the Stage

12/3/2025 15
• A JavaFX application will have three major components
namely Stage, Scene and Nodes as shown in the following diagram.

12/3/2025 16
Stage
• A stage (a window) contains all the objects of a JavaFX application. It is
represented by Stage class of the package [Link]. 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).


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

12/3/2025 17
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 [Link] 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.
12/3/2025 18
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.
• The Node Class of the package [Link] represents a node in
JavaFX, this class is the super class of all the nodes.

12/3/2025 19
Major components of in JavaFX

Component Description

Stage The top-level container (like a window).

Scene The container for all the UI elements (nodes).

Visual components like buttons, labels, text fields,


Nodes
etc.

The base class that you must extend to create a


Application
JavaFX program.

12/3/2025 20
Example: A Simple JavaFX Program Label label = new // Set the title of the window
Label("Welcome to JavaFX!"); (Stage)
// Import JavaFX libraries
// Create a button [Link]("My First
import JavaFX App");
[Link]; Button button = new
Button("Click Me"); // Add the scene to the stage
import [Link];
// Set button action [Link](scene);
import [Link];
[Link](e -> // Show the window
import [Link]; [Link]("Button Clicked!"));
[Link]();
import // Create a layout (pane) and
[Link]; add elements }
import [Link]; StackPane layout = new public static void main(String[]
StackPane(); args) {
// Launch the JavaFX
public class HelloJavaFX extends application
Application { [Link]().addAll(label,
button); launch(args);
@Override
// Create a scene and set its }}
public void start(Stage size
primaryStage) {
Scene scene = new
// Create a label Scene(layout, 300, 200);

12/3/2025 21
Line Description

extends Application Every JavaFX app must extend the Application class.

Entry point for the JavaFX app — the window setup


start(Stage primaryStage)
happens here.

Label, Button These are UI controls (Nodes).

A simple layout that stacks elements on top of each


StackPane
other.

Scene Holds all UI components for a stage (window).

Stage The window that appears on the screen.

launch(args) Starts the JavaFX application.

12/3/2025 22
JavaFx layout components
• The container in which we arrange the components is called the
Layout of the container.
• We can also say that we followed a layout as it helps in placing all the
components at a particular position within the container. Below is a
diagram illustrating the positioning of JavaFX nodes in vertical and
horizontal layout.

12/3/2025 23
JavaFx layout components
• The predefined layouts provided by JavaFX including HBox, VBox,
Border Pane, Stack Pane, Text Flow, Anchor Pane, Title Pane, Grid
Pane, Flow Panel, and so on.
• Each of the above mentioned layout is represented by a class and all
these classes belongs to the package named [Link].
To create a layout, we need to follow the given steps −
• Create node.
• Instantiate the respective class of the required layout.
• Set the properties of the layout.
• Add all the created nodes to the layout.

12/3/2025 24
JavaFx layout components
Hbox
• The HBox layout arranges all the nodes in our application in a single
horizontal row.
• The class named HBox of the package [Link] represents
the text horizontal box layout.
Vbox
• The VBox layout arranges all the nodes in our application in a single
vertical column.
• The class named VBox of the package [Link] represents
the text Vertical box layout.

12/3/2025 25
JavaFx layout components
BorderPane
• The Border Pane layout arranges the nodes in our application in top, left,
right, bottom and center positions.
StackPane
• The stack pane layout arranges the nodes in our application on top of
another just like in a stack.
• The node added first is placed at the bottom of the stack and the next node is
placed on top of it.
TextFlow
• The Text Flow layout arranges multiple text nodes in a single flow.
AnchorPane
• The Anchor pane layout anchors the nodes in our application at a particular
distance from the pane.
12/3/2025 26
JavaFx layout components
TilePane
• The Tile Pane layout adds all the nodes of our application in the form of
uniformly sized tiles.
GridPane
• The Grid Pane layout arranges the nodes in our application as a grid of
rows and columns.
• This layout comes handy while creating forms using JavaFX.
FlowPane
• The flow pane layout wraps all the nodes in a flow.
• A horizontal flow pane wraps the elements of the pane at its height,
while a vertical flow pane wraps the elements at its width.
12/3/2025 27
Basic UI controls
• UI Controls are the graphical elements that allow users to interact with an
application or a website.
• They include buttons, menus, sliders, text fields, checkboxes, radio buttons,
and more.
let's start the discussion by introducing three main aspects of an user interface
• UI elements − These are the core visual elements which the user eventually
sees and interacts with. JavaFX provides a huge list of widely used and
common elements varying from basic to complex.
• Layouts − They define how UI elements should be organized on the screen
and provide a final look and feel to the GUI (Graphical User Interface).
• Behavior − These are events which occur when the user interacts with UI
elements.

12/3/2025 28
Basic UI controls
• These controls are represented by different classes of the package
[Link].
• We can create a control by instantiating its respective class.
control Description

Label It is a component for placing text.


Button This class creates a labeled button.
ListView
A ListView component presents the user with a scrolling list of text items.

TextField A TextField object is a text component that allows for the editing of a single line
of text.
PasswordField
A PasswordField object is a text component specialized for password entry.

ColorPicker A ColorPicker provides a pane of controls designed to allow a user to manipulate


12/3/2025 and select a color. 29
Basic UI controls
Controls Descriptions
CheckBox A CheckBox is a graphical component that can be in either an on(true) or off (false)
state.

RadioButton The RadioButton class is a graphical component, which can either be in a ON (true) or
OFF (false) state in a group.

Scrollbar A Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.

FileChooser A FileChooser control represents a dialog window from which the user can select a file.
progressBar As the task progresses towards completion, the progress bar displays the task's
percentage of completion.

menubar is a graphical user interface component that displays a horizontal row of menus, each
containing a list of commands or options.
It is located at the top of a window or screen, and provides a convenient way for users to
access the functionality of an application.

12/3/2025 30
Event handling
• we can develop GUI applications, web applications and graphical applications. In
such applications, whenever a user interacts with the application (nodes), an
event is said to have been occurred.
• For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page are the activities
that causes an event to happen.
Types of Events
• The events can be broadly classified into the following two categories −
• Foreground Events − Those events which require the direct interaction of a user.
They are generated as consequences of a person interacting with the graphical
components in a Graphical User Interface. For example, clicking on a button,
moving the mouse, entering a character through keyboard, selecting an item
from list, scrolling the page, etc.
• Background Events − Those events that don't require the interaction of end-user
are known as background events. The operating system interruptions, hardware
or software failure, timer expiry, operation completion are the example of
background events.
12/3/2025 31
Events in JavaFX
• JavaFX provides support to handle a wide varieties of events.
• The class named Event of the package [Link] is the base class for an
event.
• An instance of any of its subclass is an event.
• JavaFX provides a wide variety of events. Some of them are are listed
below.
Mouse Event − This is an input event that occurs when a mouse is clicked. It
is represented by the class named MouseEvent.
• It includes actions like mouse clicked, mouse pressed, mouse released,
mouse moved, mouse entered target, mouse exited target, etc.
Key Event − This is an input event that indicates the key stroke occurred on a
node. It is represented by the class named KeyEvent.
• This event includes actions like key pressed, key released and key typed.
12/3/2025 32
Events in JavaFX
Drag Event − This is an input event which occurs when the mouse is
dragged. It is represented by the class named DragEvent.
• It includes actions like drag entered, drag dropped, drag entered
target, drag exited target, drag over, etc.
Window Event − This is an event related to window showing/hiding
actions. It is represented by the class named WindowEvent.
• It includes actions like window hiding, window shown, window
hidden, window showing, etc.

12/3/2025 33
Events in JavaFX
Event Handling is the mechanism that controls the event and decides
what should happen, if an event occurs. This mechanism has the code
which is known as an event handler that is executed when an event
occurs.
JavaFX provides handlers and filters to handle events. In JavaFX every
event has −
Target − The node on which an event occurred. A target can be a
window, scene, and a node.
Source − The source from which the event is generated will be the
source of the event. In the above scenario, mouse is the source of the
event.
Type − Type of the occurred event; in case of mouse event mouse
pressed, mouse released are the type of events.
12/3/2025 34
Events in JavaFX
Common Event Types
ActionEvent: Triggered by buttons, menu items, etc.
MouseEvent: Triggered by mouse actions (click, enter, exit, etc.).
KeyEvent: Triggered by keyboard input.

Demonstrations

12/3/2025 35
Part II

12/3/2025 36
Composite UI controls
• In JavaFX, a composite control is a control made up of multiple basic
controls to behave as a single unit.
• They are useful when you want a reusable, self-contained component
with its own logic.
• Examples:
• DatePicker – internally combines TextField + popup Calendar.
• Spinner – combines a TextField + increment/decrement buttons.
• ComboBox – TextField + dropdown list.
• TitledPane / Accordion – a container with collapsible content.
You can also create your own composite controls using HBox, VBox, or
StackPane.

12/3/2025 37
Shapes
• In JavaFX, Shapes are part of the [Link] package.
• They are 2D graphical objects that you can draw and display on the scene graph
(the window area).
• All shapes inherit from the class Shape, which provides basic properties like:
• fill → the inside color of the shape
• stroke → the border colour
• strokeWidth → the thickness of the border
Each shape can be added directly to a layout pane (like Pane, Group, or StackPane).

12/3/2025 38
Shapes
Common Properties of All Shapes

Property Description Example

setFill(Color) Sets the interior color [Link]([Link]);

setStroke(Color) Sets border color [Link]([Link]);

setStrokeWidth(double) Sets border thickness [Link](2);

setOpacity(double) Sets transparency (0.0 to 1.0) [Link](0.7);

setRotate(double) Rotates the shape [Link](45);

setTranslateX/Y(double) Moves the shape [Link](50);

12/3/2025 39
shapes
• Line
The simplest shape — a straight line between two points (x1, y1) and
(x2, y2).
Line line = new Line();
[Link](50);
[Link](50);
[Link](250);
[Link](50);
[Link]([Link]);
[Link](3);

12/3/2025 40
shapes
Circle
• A circular shape defined by its center and radius.
Circle circle = new Circle();
[Link](150);
[Link](100);
[Link](60);
[Link]([Link]);
[Link]([Link]);
[Link](3);

12/3/2025 41
shapes
Rectangle
A four-sided shape defined by its top-left corner (x, y), width, and height.
Rectangle rect = new Rectangle();
[Link](50);
[Link](50);
[Link](200);
[Link](100);
[Link]([Link]);
[Link]([Link]);
[Link](20); // rounded corner X Radius
[Link](20); // rounded corner Y radius

12/3/2025 42
shapes
Polygon
A closed shape made of multiple connected points.
Polygon polygon = new Polygon();
[Link]().addAll(100.0, 50.0, 200.0, 150.0, 100.0, 250.0,
0.0, 150.0);
[Link]([Link]);
[Link]([Link]);

12/3/2025 43
Shapes
How Shapes Are Displayed
All shapes are nodes in the JavaFX Scene Graph.
You must add them to a layout container (like a Group or Pane) to make
them visible.
Group root = new Group();
[Link]().addAll(line, circle, rect);
Scene scene = new Scene(root, 400, 300, [Link]);
[Link](scene);
[Link]();

12/3/2025 44
Shapes
Colour
In JavaFX, you can set the color of shapes, text, backgrounds, and more
using the Color class.
Common ways to create colors:
import [Link];
Color red = [Link]; // predefined color
Color custom = [Link](100, 150, 200); // custom RGB color
Color semiTransparent = [Link](0, 1, 1, 0.5); // with
opacity

12/3/2025 45
Shapes
Apply color to shapes:
Circle circle = new Circle(50); // radius 50
[Link]([Link]); // fill color
[Link]([Link]); // border color
[Link](3); // border thickness
Text
Text in JavaFX is used to display text on the scene.
import [Link];
Text text = new Text("Hello JavaFX!");
[Link](50); // position
[Link](100);
[Link]([Link]); // text color

12/3/2025 46
Shapes
Fonts
You can customize the font of your text using the Font class:
import [Link];
[Link]([Link]("Arial", 24)); // Arial, size 24
[Link]([Link]("Verdana", [Link], 30)); // bold Verdana, size 30

12/3/2025 47
Shapes
CSS Styling
• CSS, also referred to as Cascading Style Sheet, is a simple design language intended to
simplify the process of making web pages presentable and user friendly.
• It allows us to define the appearance of user interface elements of a web page.
• Using CSS, we can control the color of the text, style of fonts, spacing between
paragraphs, size of columns and layout.
• We can also control the background images or colors that are used, layout designs,
variations in viewport for different devices and screen sizes as well as a variety of other
effects.
• Generally, CSS is widely used in web development, but it can also be
applied to JavaFX application.
• In this section, we are going to learn how to use the CSS in JavaFX
application.
12/3/2025 48
Shapes
CSS Styling
• JavaFX provides us the facility of using CSS to enhance the look and feel of
the application.
• The package [Link] contains the classes that are used to apply CSS for
JavaFX applications.
• A style rule is made of three parts, which are as follows −
• Selector − A selector is an HTML tag at which a style will be applied. This could be
any tag like <h1> or <table>, etc.
• Property − A property is a type of attribute of the HTML tag. In simpler terms, all the
HTML attributes are converted into CSS properties. They could be color, border, etc.
• Value − Values are assigned to properties. For example, a color property can have
value either red or #F1F1F1, etc.

12/3/2025 49
Shapes
CSS Styling

The default style sheet used by JavaFX is [Link]. It is found in the JavaFX
runtime jar.
Adding Style Sheet in JavaFX
we can add our own style sheet to a scene in JavaFX using the
getStylesheets() method as shown below −

12/3/2025 50
CSS Styling
Adding Inline Style Sheets in JavaFX
we can also add in-line styles using the setStyle() method.
These styles consist of only key-value pairs and they are applicable to the nodes on
which they are set. Following is a sample code of setting an inline style sheet to a
button.
Looks the following pictures.

Before applying CSS After applying CSS

12/3/2025 51
Properties and bindings
• A property in JavaFX is a special variable that
• stores a value
• can be observed-Other objects can monitor changes to its value.
• can automatically update UI controls
• Example
StringProperty name = new SimpleStringProperty("Melese");
IntegerProperty age = new SimpleIntegerProperty(25);
DoubleProperty salary = new SimpleDoubleProperty(5000.0);
BooleanProperty active = new SimpleBooleanProperty(true);
• Using get() and set()
Properties are accessed with:
.get() — read value
.set() — modify value
12/3/2025 52
Properties and bindings
Example
[Link]([Link]()); // Melese
[Link]("Abebe");
Adding Listeners
• A listener is a piece of code you attach to a property to monitor its value.
• Listeners fire when the property changes.
Example
[Link]((obs, oldValue, newValue) -> {
[Link]("Name changed from " + oldValue + " to " + newValue);
});
[Link]("Kebede");
Output
12/3/2025 53
Name changed from Melese to Kebede
Properties and bindings
What Is Binding?
• Binding means linking one property to another.
• When source changes → target updates automatically
• No need to write listeners manually
Unidirectional Binding
• A depends on B
• A updates automatically if B changes.
• But changing A does NOT affect B.
Example
SimpleIntegerProperty width = new SimpleIntegerProperty(100);
SimpleIntegerProperty height = new SimpleIntegerProperty();
[Link]([Link](2)); // height = width * 2
[Link](150); // height becomes 300
12/3/2025 54
Properties and bindings
What Is Binding?
Bidirectional Binding
• Both properties update each other.
• Changing A updates B.
• Changing B updates A.
Example
SimpleStringProperty firstName = new SimpleStringProperty("Alice");
SimpleStringProperty alias = new SimpleStringProperty();
[Link](alias);
[Link]("Bob"); // firstName becomes "Bob"
[Link]("Charlie"); // alias becomes "Charlie"

12/3/2025 55
Graphics and Animation
• JavaFX provides a powerful set of APIs[Application Programming Interfaces.] for drawing shapes,
styling them, and animating UI elements.
• JavaFX graphics mainly involve:
• Colors, Text, and Fonts
• Shapes
JavaFX Animation
• JavaFX provides built-in animation classes such as:
• TranslateTransition – Move object
• RotateTransition – Rotate object
• ScaleTransition – Increase/Decrease size
• FadeTransition – Change transparency
• SequentialTransition – One after another
• ParallelTransition – At the same time
• Timeline – Per-frame animations
56
Thank you

12/3/2025 57

You might also like