[Go to site: main page, start]

0% found this document useful (0 votes)
4 views86 pages

Chapter 10 - Java GUI Using JavaFX

Chapter 10 of 'Modern Programming Practices with Java' focuses on Graphical User Interfaces (GUIs) using JavaFX, highlighting its advantages, disadvantages, and comparison with AWT and Swing. It details the architecture of JavaFX, including key components like the Scene Graph, various nodes, and the lifecycle of a JavaFX application. Additionally, it covers building blocks for creating JavaFX applications, such as stages, scenes, controls, events, and multimedia support.

Uploaded by

Adamu Tiruneh
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)
4 views86 pages

Chapter 10 - Java GUI Using JavaFX

Chapter 10 of 'Modern Programming Practices with Java' focuses on Graphical User Interfaces (GUIs) using JavaFX, highlighting its advantages, disadvantages, and comparison with AWT and Swing. It details the architecture of JavaFX, including key components like the Scene Graph, various nodes, and the lifecycle of a JavaFX application. Additionally, it covers building blocks for creating JavaFX applications, such as stages, scenes, controls, events, and multimedia support.

Uploaded by

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

Modern Programming

Practices with Java

Instructor: Solomon (Ph.D)


Chapter 10: GUI using JavaFX
Graphical User Interface (GUI)
• A Graphical User Interface (GUI) is a user-friendly
interface that allows users to interact with
computers, applications, or devices through graphical
elements such as buttons, icons, menus, and
windows, instead of relying on text-based
commands.
• Advantages of GUI:
– User-Friendly: Easier to learn and use compared to
command-line interfaces.
– Intuitive Design: Allows users to perform tasks with
minimal instruction.
– Enhanced Visual Appeal: Makes software more appealing
and engaging.
Graphical User Interface (GUI) …
• Disadvantages of GUI:
– Resource-Intensive: Requires more memory and processing
power compared to text-based interfaces.
– Complexity in Design: Developing a good GUI can be time-
consuming and challenging.
• Examples of GUI:
✓ Operating systems: Microsoft Windows, macOS, Linux, and
so on.
✓ Applications: Web browsers, word processors, and video
editing software.
✓ Mobile devices: Interfaces of Android and iOS smartphones.
Graphical User Interface (GUI) …
• Java provides several APIs for GUI programming,
enabling developers to build rich and interactive
desktop applications.
• Below are the main sets of Java APIs for GUI
programming:
– AWT (Abstract Window Toolkit)
• Was the first GUI toolkit introduced in Java.
• Offers basic GUI components like buttons, labels, text fields, etc.
• Limited in functionality compared to more modern toolkits.
– Swing
• Is a more advanced and versatile GUI toolkit built on top of AWT.
• Provides a richer set of components compared to AWT.
– JavaFX
Comparison of AWT, Swing, and JavaFX
Feature AWT Swing JavaFX
Platform Platform- Platform- Platform-
Dependency dependent independent independent

Styling Limited Customizable (via Advanced (via CSS)


Look & Feel)

Ease of Use Simple, but More versatile than Modern, supports


limited AWT advanced UIs

Graphics Basic Improved over Advanced 2D/3D,


Support AWT animations

Current Outdated Still used but Actively supported


Status declining and modern
What is JavaFX?
• It is a modern GUI (Graphical User Interface) framework
for building desktop applications, rich internet
applications (RIAs), and multimedia applications in Java.
– It serves as the successor to Swing and AWT, providing a more
flexible, efficient, and visually appealing way to design user
interfaces.
• The applications developed using JavaFX can run on
various devices such as Desktop Computers, Mobile
Phones, TVs, Tablets, etc.
• Where JavaFX is used:
– Desktop applications (e.g., media players, dashboards)
– Simulation and visualization tools
– Educational and data visualization software
– Rich internet applications (when embedded in web views)
JavaFX Architecture
• 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 RIAs
and GUI applications with intense graphics that can run
consistently over multiple platforms.
Key Components of JavaFX Architecture
• Glass Window Toolkit:
– Low-level layer that interacts directly with the native operating
system for rendering windows, events (e.g., mouse, keyboard,
touch), and input/output.
• Prism:
– A high-performance graphics engine responsible for rendering 2D
and 3D graphics. It uses hardware-accelerated rendering through
OpenGL, DirectX, or software rendering as a fallback.
• Media Engine:
– Supports multimedia features in JavaFX.
– Enables: Audio playback (e.g., MP3, WAV), & Video playback (e.g.,
MP4, H.264).
• Web Engine:
– A web rendering engine based on WebKit.
– Used for embedding web content in JavaFX applications.
– Supports: HTML, CSS, and JavaScript.
Key Components of JavaFX Architecture

• Quantum Toolkit:
– Acts as a bridge between the Glass Window Toolkit, Prism, and
the JavaFX Scene Graph, ensuring smooth communication
between layers.
• Scene Graph:
– It 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.
– A single component in a scene graph is known as a node.
– 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).
Key Components of JavaFX Architecture

– The nodes are of three general types. These are as follows:
▪ Root Node - is a node that does not have any node as its
parent.
▪ Branch Node - is a node that contains a node as its parent and
also has a node as its children.
▪ Leaf Node - is a node that does not contain any node as its
children.
Key Components of JavaFX Architecture

• JavaFX API (Developer Interface):
– Provides developers with tools to design and control the user
interface, manage multimedia, and implement animations.
– Major APIs:
▪ [Link]: Provides classes to launch and manage JavaFX
applications.
▪ [Link]: Contains classes related to the scene graph (the hierarchy
of nodes that make up the UI).
▪ [Link]: Provides layout containers for arranging UI
components.
▪ [Link]: Contains standard UI controls like buttons, labels,
text fields, etc.
▪ [Link]: Contains classes for drawing shapes and creating
graphical content.
▪ [Link]: Provides classes for displaying and manipulating text in
JavaFX applications.
▪ [Link]: Provides classes for loading and displaying images.
Key Components of JavaFX Architecture

▪ [Link]: Contains classes for creating and managing
animations.
▪ [Link]: Provides classes for applying visual effects to nodes
(like shadows, blurs, etc).
▪ [Link]: Contains classes for handling input events, such as
mouse clicks, keyboard events, and touch events.
▪ [Link]: Provides classes related to the stage (the top-level
window).
▪ [Link]: Contains classes for integrating web content into
JavaFX applications.
▪ [Link]: Provides classes for working with properties and bindings.
▪ [Link]: Contains utility classes for various tasks.
▪ [Link]: Provides classes for concurrent tasks, useful for
running background operations.
▪ [Link]: Contains classes for working with colors, gradients,
and patterns in JavaFX.
▪ [Link]: Contains classes for styling JavaFX components using CSS.
Interaction Between Components of
JavaFX Architecture
1) User Input:
– Events like clicks or key presses are captured by the Glass
Window Toolkit.
2) Scene Graph Updates:
– The input is processed, and changes are applied to the Scene
Graph.
3) Rendering:
– The Quantum Toolkit passes the updated Scene Graph to Prism.
– Prism renders the graphics using GPU acceleration.
4) Media Playback:
– If multimedia is involved, the Media Engine handles audio/video
processing.
5) Web Content:
– For web elements, the Web Engine renders the content within the
application.
Lifecycle of JavaFX Application
• The lifecycle of a JavaFX application is defined by
three primary phases: initialization, execution, and
termination.
– These phases correspond to specific methods that the
developer can override in the JavaFX Application class.
Lifecycle of JavaFX Application …
1) Initialization Phase (init())
– This method is called before the application starts.
– Used to perform setup tasks like initializing resources (e.g., loading
configurations, preparing data).
– Does not involve any graphical operations (as the UI toolkit is not yet
loaded).
– It’s optional to override this method.
2) Execution Phase (start(Stage primaryStage))
− This is the main entry point for the JavaFX application.
− The Stage object (primaryStage) is the top-level container for the JavaFX
application.
− Responsibilities:
▪ Setup the user interface by:
✓ Creating a scene graph (hierarchy of UI elements), and
✓ Setting the Scene onto the Stage.
▪ Display the stage using [Link]().
− This method must be overridden as it defines the application’s visual structure.
Lifecycle of JavaFX Application …
3) Termination Phase (stop())
– Called when the application is about to exit.
– Used for cleanup tasks such as releasing resources or saving
state.
– It’s optional to override this method.
– Triggered when:
▪ The user closes the application window.
▪ The [Link]() method is called.
▪ An Exception occurs that terminates the application.
Demonstrating JavaFX Lifecycle
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class JavaFXLifecycleExample extends Application {


@Override
public void init() {
[Link]("Initialization Phase: Resources loaded.");
}
@Override
public void start(Stage primaryStage) {
[Link]("Execution Phase: Setting up UI.");
Label label = new Label("Hello JavaFX!");
StackPane root = new StackPane(label);
Scene scene = new Scene(root, 300, 200);
[Link]("JavaFX Lifecycle Example");
[Link](scene);
[Link]();
}
@Override
public void stop() {
[Link]("Termination Phase: Cleaning up resources.");
}
public static void main(String[] args) { Initialization Phase: Resources loaded.
launch(args);
}
Execution Phase: Setting up UI.
} Termination Phase: Cleaning up resources.
Building Blocks of JavaFX
• The building blocks of JavaFX form the foundation for
creating rich, and interactive GUIs. These components are
hierarchical and modular, making it easier for developers
to design scalable and maintainable applications.
1) Application
− The Application class is the entry point for all JavaFX applications.
− It provides the basic structure for starting, running, and stopping
a JavaFX program.
− We can create a JavaFX application by extending the
[Link] class.
2) Stage
− The Stage is the top-level container that represents a window in
a JavaFX application.
Building Blocks of JavaFX …
– Types of Stages:
▪ Primary Stage: Automatically created and passed to the start()
method.
public void start(Stage primaryStage) {
[Link]("MyJavaFX");
[Link]();
}

▪ Secondary Stages: Additional windows can be created using new


Stage().
private void openSecondaryStage() {
// Create a new Stage (Secondary Stage)
Stage secondaryStage = new Stage();
[Link]("Secondary Stage");
[Link]();
}

3) Scene
− The Scene is the container for all graphical elements in a JavaFX
application.
− It contains a root node, which is the starting point of the scene graph.
− A single stage can display one scene at a time.
Building Blocks of JavaFX …
Scene scene = new Scene(new VBox(), 400, 300); // VBox is the root node
[Link](scene);

4) Scene Graph
− It is the hierarchical structure of nodes in a JavaFX application. It starts
with a root node and contains all visual elements as child nodes.
− Hierarchy:

5) Nodes
− A Node is the fundamental building block of the scene graph. Everything
you see in a JavaFX application is a type of node.
− Types of Nodes:
▪ Shape Nodes: Used for drawing shapes (e.g., Rectangle, Circle, Line).
▪ UI Controls: Interactive components like Label, Button, TextField.
▪ Containers (Parent Nodes): Used to layout other nodes (e.g., VBox,
GridPane).
Building Blocks of JavaFX …
Button btn = new Button("Click Me");
Label lbl = new Label("Welcome to JavaFX");

6) Layout Containers
− Are parent nodes that help to arrange child nodes in the scene.
− Common Layouts:
▪ StackPane: Stacks all children on top of each other.
▪ VBox: Arranges children vertically.
▪ HBox: Arranges children horizontally.
▪ GridPane: Arranges its children in a grid of rows and columns.
▪ BorderPane: Divides the scene into five regions: top, bottom, left, right,
center.
VBox vbox = new VBox();
[Link]().addAll(new Button("Button 1"), new Button("Button 2"));

7) Controls
− JavaFX provides a rich set of controls for creating user interfaces.
− Examples:
▪ Text Inputs: TextField, PasswordField, TextArea
Building Blocks of JavaFX …
▪ Buttons: Button, ToggleButton
▪ Choice Controls: ComboBox, ChoiceBox, CheckBox, RadioButton
▪ Menus: MenuBar, Menu, ContextMenu
▪ Sliders: Slider, ProgressBar, ProgressIndicator
Button btn = new Button("Submit");
TextField txtField = new TextField();

8) Events and Event Handling


− JavaFX uses an event-driven model for handling user interactions.
− Common Event Types:
▪ Mouse Events: Clicks, drags, and movements.
▪ Keyboard Events: Key presses and releases.
▪ Action Events: Button clicks, menu item selections.
[Link](e -> [Link]("Button clicked!"));

9) CSS Styling
− JavaFX supports CSS for styling the UI components.
.button {
-fx-background-color: blue; Apply CSS to the scene:
-fx-text-fill: white; [Link]().add("[Link]");
}
Building Blocks of JavaFX …
10) FXML (Declarative UI Design)
− It is an XML-based language used to define the UI structure
declaratively.
− Advantages:
▪ Separates UI design from application logic.
▪ Simplifies development.
// [Link]
<VBox xmlns:fx="[Link]
<Label text="Hello JavaFX!"/>
<Button text="Click Me"/>
</VBox>

// Java Code
Parent root = [Link](getClass().getResource("[Link]"));
Scene scene = new Scene(root, 400, 300);
[Link](scene);

11) Animation and Effects


− JavaFX provides tools to create dynamic UIs using animations and
visual effects.
Building Blocks of JavaFX …
− Examples of Animations:
▪ TranslateTransition (move objects).
▪ RotateTransition (rotate objects).
▪ FadeTransition (fade in/out).
// Java Code
TranslateTransition transition = new TranslateTransition([Link](1), button);
[Link](100); // Move 100px on X-axis
[Link]();

12) Multimedia and Web


− Supports playback of audio and video files using Media and
MediaPlayer.
− Embed web content using WebView and WebEngine.
− Example:
// Java Code
WebView webView = new WebView();
[Link]().load("[Link]
Building Blocks of JavaFX - Summary
Building Block Description Example
Application Entry point for JavaFX extends Application
apps
Stage Top-level window [Link]("My App")
container
Scene Content area for nodes new Scene(root, 400, 300)
Node Basic UI component new Button("Submit")
Layout Arranges nodes new VBox()
Controls Interactive elements Button, TextField, Slider
FXML Declarative UI design [Link]()
Events Handles user setOnAction(e -> { ... })
interactions
Animation Adds dynamic behavior TranslateTransition,
to the UI FadeTransition
CSS Styling Customizes appearance [Link]().add(...)
Your First JavaFX Application
• Below is a simple example of creating a JavaFX application
that opens a window with a "Hello World!" message.
• Step 1: Install VS Code
• Step 2: Install Java and JavaFX
– Install Java JDK (jdk-23)
– Download JavaFX SDK:
▪ Go to the JavaFX website and download the latest JavaFX SDK.
▪ Extract the JavaFX SDK to a folder on your computer.
• Step 3: Install Extensions in VS Code
− Install Java Extensions:
▪ Language Support for Java(TM) by Red Hat, Debugger for Java, Java
Test Runner, Maven for Java (optional but helpful if using Maven),
Visual Studio Code Java Pack Installer.
− Install JavaFX Support (optional but recommended)
• Step 4: Configure the JavaFX SDK in VS Code
Your First JavaFX Application …
• Step 5: Test the Setup
− Create a simple JavaFX application like the following and run it
from VS Code:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class HelloWorldButtonApp extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button("Click Me!"); // Create a Button
// Set an action for the button, which prints to the console
[Link](event -> [Link]("Hello World!"));
// Create a layout and add the button to it
StackPane root = new StackPane();
[Link]().add(btn);
// Create a Scene and set it to the Stage
Scene scene = new Scene(root, 300, 200);
[Link]("Hello World Button App");
[Link](scene);
[Link](); // Show the Stage
}
public static void main(String[] args) {
launch(args); // Called in the main()
} // Used to initiate the JavaFX App
}
JavaFX Layouts
Layouts
• They are containers used to arrange UI components
(nodes) in a structured and visually pleasing manner.
• They help to organize the nodes within the scene graph
and define their position, alignment, spacing, and sizing.
• The JavaFX layout classes are part of the
[Link] package.
• Types of JavaFX Layouts:
1) Pane
− It places nodes at their coordinates without applying additional
layout rules.
− Example:
Button btn = new Button("Click Me");
[Link](100);
[Link](50);

Pane pane = new Pane();


[Link]().add(btn);
Types of Layouts
2) StackPane
− Arranges all child nodes in a single stack, one on top of the other,
centered by default.
− Example:
Circle circle = new Circle(100);
[Link]([Link]);
Label label = new Label("Hello Circle!");
StackPane stackPane = new StackPane();
[Link]().addAll(circle, label);

3) HBox (Horizontal Box)


− Arranges its children in a single horizontal row.
− Example:
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
Button btn3 = new Button("Button 3");
HBox hBox = new HBox(10); // 10px spacing
[Link]().addAll(btn1, btn2, btn3);

4) VBox (Vertical Box)


− Arranges its children in a single vertical column.
− Example:
Types of Layouts …
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
VBox vBox = new VBox(10); // 10px spacing
[Link]().addAll(btn1, btn2);

5) GridPane
− Arranges its children in a grid of rows and columns.
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
Button btn3 = new Button("Button 3");
Button btn4 = new Button("Button 4");

GridPane gridPane = new GridPane();


[Link](10); // Horizontal gap
[Link](10); // Vertical gap
[Link](btn1, 0, 0); // Column 0, Row 0
[Link](btn2, 1, 0); // Column 1, Row 0
[Link](btn3, 0, 1); // Column 0, Row 1
[Link](btn4, 1, 1); // Column 1, Row 1

6) BorderPane
− Divides the layout into five regions: top, bottom, left, right, and
center.
− Example:
Types of Layouts …
Button topButton = new Button("Top");
Button centerButton = new Button("Center");

BorderPane borderPane = new BorderPane();


[Link](topButton);
[Link](centerButton);

7) FlowPane
− Arranges its children in a row (horizontally) or column (vertically) and
moves to the next row/column when there’s no more space.
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
Button btn3 = new Button("Button 3");
Button btn4 = new Button("Button 4");
Button btn5 = new Button("Button 5");
// new FlowPane([Link]);
FlowPane flowPane = new FlowPane();
[Link](10); // Horizontal gap
[Link](10); // Vertical gap
[Link]().addAll(btn1, btn2, btn3, btn4, btn5);

8) TilePane
− Arranges its children in uniformly sized tiles.
− The tiles can flow either horizontally (default) or vertically,
depending on the pane’s orientation.
Types of Layouts …
// Create some Buttons
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
Button btn3 = new Button("Button 3");
Button btn4 = new Button("Button 4");
Button btn5 = new Button("Button 5");

// Create a TilePane with vertical flow


TilePane tilePane = new TilePane([Link]);
[Link](10); // Vertical gap between tiles

// Add Buttons to the TilePane


[Link]().addAll(btn1, btn2, btn3, btn4, btn5);
JavaFX UI Controls
UI Controls
• JavaFX provides a rich set of UI controls for building
modern and interactive GUIs.
• These controls are part of the JavaFX API and are located
in the [Link] package.
• Basic Controls:
1) Label
− Used to display non-editable text in the UI.
− Example:
Label label = new Label("Hello JavaFX!");

2) Button
− Used to trigger actions when clicked.
− Example:
Button btn = new Button("Click Me");
[Link](e -> [Link]("Button clicked!"));

3) TextField
− Used for single-line text input.
UI Controls …
− Example:
TextField txtField = new TextField();
[Link]("Enter your name");

4) PasswordField
− A single-line text input for entering password text.
− Example:
PasswordField pwdField = new PasswordField();

5) TextArea
− Allows users to enter multi-line text.
− Example:
TextArea txtArea = new TextArea();
[Link]("Enter your comments here …");

• Selection Controls:
6) CheckBox
− Allows users to select one or more options.
− Often used for binary choices (checked or unchecked).
− Example:
CheckBox checkBox = new CheckBox("I agree to the terms and …");
UI Controls …
7) RadioButton
− Allows the user to select one option from a group.
− Multiple radio buttons are typically grouped together in a
ToggleGroup so that only one can be selected at a time.
RadioButton rb1 = new RadioButton("Option 1");
RadioButton rb2 = new RadioButton("Option 2");
RadioButton rb3 = new RadioButton("Option 3");
ToggleGroup tGroup = new ToggleGroup();
[Link](tGroup);
[Link](tGroup);
[Link](tGroup);

8) ComboBox
− A drop-down menu for selecting a single item
from a list of options.
ComboBox<String> comboBox = new ComboBox<>();
[Link]().addAll("Option1","Option2","Option3");

9) ListView
− Displays a list of items that can be selected.
ListView<String> listView = new ListView<>();
[Link]().addAll("Item 1","Item 2","Item 3");
UI Controls …
10) ChoiceBox
− Allows users to select a single item from a list of options.
− Unlike a ComboBox, a ChoiceBox shows only the selected item when
collapsed.
− Example:
ChoiceBox<String> choiceBox = new ChoiceBox<>();
[Link]().addAll("Option 1","Option 2","Option 3"););

• Date and Time Controls:


11) DatePicker
− A control for selecting a date.
− Example:
DatePicker datePicker = new DatePicker();

• These controls can be styled using CSS for custom designs


and combined within layout containers such as VBox,
HBox, GridPane, or BorderPane to build comprehensive
GUIs.
JavaFX Shapes
Shapes
• In JavaFX, shapes are used to represent graphical
elements such as lines, circles, rectangles, polygons, etc.
• These shapes are part of the [Link] package.
• Here are some common shapes in JavaFX:
1) Rectangle
− It is defined by its width, height, and position (x and y coordinates).
− Example:
Rectangle rectangle = new Rectangle(100, 100, 200, 150); // (x,y,w,h)
[Link]([Link]);

2) Circle
− It is defined by its center coordinates (x, y) and its radius.
− Example:
Circle circle = new Circle(200, 200, 50); // (centerX, centerY, radius)
[Link]([Link]);
Shapes …
3) Line
− It is defined by its start and end coordinates.
− Example:
Line line = new Line(50, 50, 350, 350); // (x1, y1, x2, y2)
[Link]([Link]);

4) Polygon
− It is defined by a series of points. You can specify the points of the
shape.
− Commonly used methods:
▪ getPoints(): Returns a list of points that make up the polygon. Each
point is represented by a pair of x and y coordinates.
Polygon polygon = new Polygon();
[Link]().addAll(100.0,100.0,200.0,100.0,200.0,200.0,100.0,200.0);

▪ setFill(Paint p): Sets the fill color of the polygon. The Paint parameter
allows you to set colors using Color.
[Link]([Link]); // Fills the polygon with a solid red color
Shapes …
6) Ellipse
− It is defined by its center coordinates (x, y), horizontal radius, and
vertical radius.
− Example:
Ellipse ellipse = new Ellipse(200, 200, 100, 50); // (centerX, centerY, radiusX,
// radiusY)
[Link]([Link]);
Color, Text and Font
1) Color:
− JavaFX uses the Color class to represent colors.
− Provides several predefined colors such as [Link],
[Link], [Link], etc.
2) Text:
− JavaFX provides the Text class for displaying simple text on the
screen.
− You can customize the appearance of the text, such as its color,
font, and position.
3) Font:
− JavaFX uses the Font class to define the appearance of text, such
as its size, family, etc.
− You can set a font directly on a Text node.
Color, Text and Font …
− Example:
import [Link];
import [Link];
import [Link];

// Create text with custom font


Text text = new Text("JavaFX Text and Font");
[Link]([Link]); // Set text color to white

Font font = [Link]("Arial", 24); // Set font to Arial, size 24


[Link](font);
JavaFX Event Handling
Intro to Event Handling
▪ JavaFX provides an event-handling mechanism that allows
you to respond to user interactions with GUI components
like buttons, text fields, and so on.
▪ The event-handling process in JavaFX typically involves
registering an event handler for a specific event and then
responding to that event when it occurs.
▪ Basic Concepts of Event Handling in JavaFX:
▪ Event Sources: These are the components that trigger events (e.g., a
button, a text field, etc).
▪ Event Types: These are the different kinds of actions that can
happen (e.g., mouse click, key press, etc).
▪ Event Handlers: These are the methods that are invoked when an
event occurs. They define how to respond to a specific event.
Steps for Event Handling in JavaFX
1) Create a GUI Component: This could be a button, text
field, etc.
2) Create an Event Handler: A handler method that
processes the event.
3) Register the Event Handler: Attach the event handler to
the GUI component.
• Example: Handling Button Click Events
// Create a button
Button btn = new Button("Click Me!");

// Create an event handler for the button click event


[Link](e -> [Link]("Button was clicked!"));

Note:
✓ setOnAction: This method registers an event handler for the button’s
action event (which occurs when the button is clicked).
✓ Lambda Expression: The event handler uses a lambda expression to define
the behavior when the button is clicked (printing a message).
Event Handler Interface
• JavaFX allows you to implement event handlers in different
ways:
1) Using Anonymous Classes:
− You can directly define a class for the event handler without
explicitly creating a separate class.
− Example: Handling a Button Click Event with an Anonymous
Class.
// Using an anonymous class for the event handler
[Link](new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
[Link]("Button clicked using an anonymous class!");
}
});

▪ In this example:
− The event handler is created using an anonymous class that implements the
EventHandler interface for handling the ActionEvent.
Event Handling Interface …
2) Using Lambda Expressions:
− Lambda expressions allow you to define event handlers concisely
in a functional style.
− They are commonly used for short and simple event handlers.
− Example: Handling a Button Click Event with Lambda Expression.
// Lambda expression for event handling
[Link](event -> [Link]("Button clicked using lambda!"));

▪ In this example:
− The setOnAction method uses a lambda expression to handle the
button click event.
− The lambda is short and functional, making the code more readable
and concise.
Event Handling Interface …
• JavaFX provides several “convenience methods” for event
handling.
• These methods allow developers to easily attach handlers
for common events, such as mouse clicks or key presses.
• Examples:
− setOnAction(): For handling actions like button clicks.
− setOnMouseClicked(): For handling mouse clicks.
− setOnKeyPressed(): For handling key presses.

Examples:
[Link](e -> [Link]("Action performed on button!"));

[Link](e -> [Link]("Mouse clicked on button!"));

[Link](e -> [Link]("Key pressed: " + [Link]()));


JavaFX Composite UI Controls
Intro to Composite UI Controls
• In JavaFX, composite UI controls are UI components that
combine multiple basic controls into a single functional
unit.
• These controls allow developers to create complex and
reusable components, making the code more modular
and easier to maintain.
• Advantages of Composite UI Controls:
✓ Reusability: Code for the composite control can be reused across
multiple applications.
✓ Maintainability: Encapsulating UI logic in a composite control
simplifies debugging and updates.
✓ Customizability: Developers can tailor composite controls to
specific application needs.
✓ Modularity: Promotes separation of concerns by breaking the UI
into smaller, reusable parts.
Building Blocks of Composite UI Controls
• Composite UI controls often include:
– Layouts: Containers like VBox, HBox, GridPane, or BorderPane to
arrange child nodes.
– Basic UI Controls: Components like Button, TextField, Label, etc.
– Event Handlers: Logic to handle user interactions with the
controls.
– Properties and Bindings: They let values inside UI components
stay in sync automatically, reducing the need for manual event
handling.
– CSS Styling: Styling using JavaFX’s CSS to give a unique
appearance.
JavaFX CSS Styling
Intro to CSS Styling
• JavaFX allows developers to enhance the visual appeal of
their applications by applying styles using Cascading Style
Sheets (CSS).
• JavaFX CSS is based on W3C standards with extensions
specific to JavaFX.
• Why use CSS in JavaFX?
– Separation of Design and Logic: Keeps design separate from the
application logic.
– Reusability: The same CSS can style multiple components,
reducing redundancy.
– Flexibility: Easy to update and maintain the look and feel of the
application.
Basics of JavaFX CSS
• A JavaFX CSS file has a .css extension.
• You can attach a CSS file to your JavaFX scene or specific
components using:
[Link]().add("[Link]");

• JavaFX CSS uses selectors like traditional CSS:


− Tag Selectors: Targets all nodes of a specific type.
Button {
-fx-background-color: lightblue;
}

− ID Selectors: Targets a specific node with an ID.


#uniqueButton {
-fx-font-size: 16px;
}

Assign in JavaFX code: [Link]("uniqueButton");


Basics of JavaFX CSS …
− Class Selectors: Targets nodes with a specific class.
.roundedButton {
-fx-background-radius: 10;
}

Assign in JavaFX code: [Link]().add("roundedButton");

• Commonly Used JavaFX CSS Properties:


− Background Color:
.example {
-fx-background-color: #ffcc00;
}

− Font:
.example {
-fx-font-size: 18px;
-fx-font-family: "Arial";
-fx-font-weight: bold;
}
Basics of JavaFX CSS …
− Padding and Margin (using Insets): -fx-padding: Adds space
inside the element; -fx-margin: Adds space outside the element.
.example {
-fx-padding: 10px 20px; /* 10px top-bottom, 20px left-right */
}

− Border:
.example {
-fx-border-color: blue;
-fx-border-width: 2px;
}

– Effect (e.g., shadow): -fx-effect: Applies an effect to a component


(like shadow).
.example { /* dropshadow - a shadow that falls behind the element.*/
-fx-effect: dropshadow(gaussian, black, 10, 0.5, 2, 2);
}
Note:
✓ A gaussian shadow creates a soft, blurred shadow with smooth edges, compared to a hard-edged shadow.
✓ black - This specifies the color of the shadow.
✓ 10: This value is the radius of the blur effect.
✓ 0.5: This is the spread of the shadow, which determines how much the shadow expands out from the edge of
the element. A value of 0.5 means a moderate spread.
✓ 2, 2: These are the horizontal and vertical offsets of the shadow.
Examples
• Example 1: Styling Buttons
CSS File:
.btn {
-fx-background-color: #FF6347; /* Tomato color */
-fx-text-fill: white;
-fx-font-size: 14px;
-fx-padding: 5 15;
}

Java Code:
Button btn = new Button("Click Me");
[Link]().add("btn");

• Example 2: Styling a Scene


CSS File:
.root {
-fx-background-color: #f0f8ff;
}

Java Code:
StackPane root = new StackPane();
Scene scene = new Scene(root, 400, 300);
[Link]().add("[Link]");
Examples …
• Example 3: Styling a Label with ID
CSS File:
#highlightedLabel {
-fx-font-size: 20px;
-fx-font-weight: bold;
-fx-text-fill: green;
}

Java Code:
Label lbl = new Label("Hello JavaFX!");
[Link]("highlightedLabel");
Advanced Styling
• Pseudo-Classes: JavaFX components have pseudo-classes
like :hover, :focus, :pressed.
.button:hover {
-fx-background-color: darkorange;
}

• Customizing Scrollbars
.scroll-bar {
-fx-background-color: lightgray;
}
JavaFX Properties and Bindings
Intro to Properties and Bindings
• JavaFX provides a powerful mechanism to manage
the state of objects and establish dynamic
relationships between objects.
• Properties:
– Observable values that can trigger listeners when their
values change.
• Bindings:
– Facilitate automatic synchronization between
properties.
Properties in JavaFX
• Properties in JavaFX are wrappers around data values
(e.g., integers, strings, etc.), allowing them to be
observable.
• Types of Properties - JavaFX offers various property
classes based on data types:
✓ SimpleIntegerProperty
✓ SimpleDoubleProperty
✓ SimpleStringProperty
✓ SimpleBooleanProperty
✓ SimpleObjectProperty
• Features of Properties:
– Properties can notify listeners when the value changes.
– Each property provides methods to get or set the value.
Properties in JavaFX …
• Common Methods in Properties:
Method Description
get() Retrieves the current value.
set(newValue) Updates the property’s value.
addListener(ChangeListener) Listens for changes to the value.
bind(ObservableValue) Binds the property to another.
unbind() Removes the binding.
Example: Properties
import [Link];

public class PropertyExample extends Application {


public void start(Stage primaryStage) {
SimpleIntegerProperty property = new SimpleIntegerProperty(10);

// Adding a listener
[Link]((observableValue, oldValue, newValue) ->
[Link]("Value changed from " + oldValue + " to " + newValue);
);

// Changing the property's value


[Link](20);
[Link](30);
}
public static void main(String[] args) {
launch(args);
}
}
Output:
Value changed from 10 to 20
Value changed from 20 to 30
Bindings in JavaFX
• Bindings in JavaFX allow you to establish dependencies
between properties.
• When a bound property changes, its dependent
properties automatically update.
• Types of Bindings:
– Unidirectional Binding: One property is bound to another, but
not vice versa. A → B (B follows A)
– Bidirectional Binding: Both properties update each other. A B
(both stay in sync)
• Creating Bindings - JavaFX provides methods to bind
properties:
– bind(ObservableValue)
– bindBidirectional(Property)
Example: Unidirectional Binding
import [Link];

public class UnidirectionalBindingExample extends Application {


public void start(Stage primaryStage) {
SimpleIntegerProperty property1 = new SimpleIntegerProperty(10);
SimpleIntegerProperty property2 = new SimpleIntegerProperty();

// Unidirectional binding
[Link](property1);

[Link]("Property2: " + [Link]()); // Output: 10

// Changing property1
[Link](25);
[Link]("Property2: " + [Link]()); // Output: 25
}
public static void main(String[] args) {
launch(args);
}
}
Output:
Property2: 10
Property2: 25
Example: Bidirectional Binding
import [Link];
public class BidirectionalBindingExample extends Application {
public void start(Stage primaryStage) {
SimpleIntegerProperty property1 = new SimpleIntegerProperty(10);
SimpleIntegerProperty property2 = new SimpleIntegerProperty(20);

// Bidirectional binding
[Link](property2);

[Link]("Property 1: " + [Link]()); // Output: 20


[Link]("Property 2: " + [Link]()); // Output: 20

// Changing property1
[Link](30);
[Link]("Property 1: " + [Link]()); // Output: 30
[Link]("Property 2: " + [Link]()); // Output: 30
}
public static void main(String[] args) { launch(args); }
}
Output:
Property 1: 20
Property 2: 20
Property 1: 30
Property 2: 30
Benefits of Properties and Bindings
• Simplifies the synchronization of UI elements.
• Dynamically updates properties and UI controls.
• Reduces boilerplate code for event handling:
– It means you don’t have to write the same long,
repetitive code every time you handle an event like a
button click or a key press.
JavaFX Graphics and Animation
Intro to Graphics and Animations
• JavaFX provides robust support for graphics and
animations, enabling developers to create rich and
interactive UIs.

• JavaFX provides two primary ways to draw graphics:


– Node-Based Graphics: Using pre-defined shapes (Rectangle,
Circle, etc) in the scene graph.
– Canvas Graphics: The Canvas node allows you to draw custom
graphics using a GraphicsContext.
Example - Node-Based Graphics
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class NodeGraphicsExample extends Application {


@Override
public void start(Stage primaryStage) {
Rectangle rectangle = new Rectangle(100, 60, [Link]);
[Link](20);
[Link](20);

StackPane root = new StackPane(rectangle);


Scene scene = new Scene(root, 400, 300);

[Link]("Node-Based Graphics Example");


[Link](scene);
[Link]();
}
public static void main(String[] args) {
launch(args);
}
}
Example - Drawing with Canvas
import [Link]; import [Link];
import [Link]; import [Link];
import [Link]; import [Link];
import [Link];

public class CanvasExample extends Application {


@Override
public void start(Stage stage) {
Canvas canvas = new Canvas(400, 300); // Create a Canvas
GraphicsContext gc = canvas.getGraphicsContext2D();
// Draw on the Canvas
[Link]([Link]);
[Link](0, 0, 400, 300);

[Link]([Link]);
[Link](50, 50, 100, 100);

StackPane stPane = new StackPane(canvas); // Add the Canvas to the StackPane


Scene scene = new Scene(stPane, 400, 300); // Set up the Scene
[Link]("JavaFX Canvas Example");
[Link](scene);
[Link]();
}
public static void main(String[] args) {
launch(args);
}
} // Output: A canvas with a gray background, and a red circle.
JavaFX Animation
• Animations in JavaFX add movement and interactivity to
graphics.
• They can be applied to visual nodes (like shapes and
images) or used to control custom graphics.
• Common types of Animations:
1) Transition Animation:
▪ Predefined animations for common effects like fading, scaling, and
rotating.
− TranslateTransition: Moves a node from one position to another.
− RotateTransition: Rotates a node around a pivot point.
− FadeTransition: Changes the opacity of a node (makes it fade in or out).
− ScaleTransition: Scales a node’s size.
2) Timeline Animation: A more flexible approach that allows
custom animations using keyframes.
Example: TranslateTransition Animation
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class TranslateTransitionExample extends Application {
@Override
public void start(Stage primaryStage) {
Circle circle = new Circle(50, [Link]);
// Create TranslateTransition
TranslateTransition transition = new TranslateTransition([Link](2), circle);
[Link](200); // Move 200 units right
[Link]([Link]);
[Link](true);
[Link]();

StackPane root = new StackPane(circle);


Scene scene = new Scene(root, 400, 300);

[Link]("Translate Transition Example");


[Link](scene);
[Link]();
}
public static void main(String[] args) {
launch(args);
}
}
Example: RotateTransition Animation
import [Link]; import [Link];
import [Link]; import [Link]; import [Link];
import [Link]; import [Link]; import [Link];
public class RotateTransitionExample extends Application {
@Override
public void start(Stage primaryStage) {
Rectangle rectangle = new Rectangle(100, 100, [Link]); // Create a Rectangle
// Create a RotateTransition for the rectangle
RotateTransition rotateTransition = new RotateTransition();
[Link](rectangle);
[Link](360); // Rotate 360 degrees
[Link]([Link]); // Repeat indefinitely
[Link](true); // Reverse the rotation after each cycle
[Link]([Link](2)); // Duration of the animation
[Link](); // Start the rotation
// Set up the scene and stage
StackPane root = new StackPane();
[Link]().add(rectangle);
Scene scene = new Scene(root, 300, 300);
[Link]("Rotate Transition Example");
[Link](scene);
[Link]();
}
public static void main(String[] args) {
launch(args);
}
}
Example: FadeTransition Animation
import [Link]; import [Link];
import [Link]; import [Link];
import [Link]; import [Link];
import [Link]; import [Link];
public class FadeTransitionExample extends Application {
@Override
public void start(Stage primaryStage) {
Rectangle rectangle = new Rectangle(200, 100, [Link]);
// Create FadeTransition
FadeTransition fade = new FadeTransition([Link](2), rectangle);
[Link](1.0); // Fully visible
[Link](0.3); // Partially transparent
[Link]([Link]);
[Link](true);
[Link]();

StackPane root = new StackPane(rectangle);


Scene scene = new Scene(root, 400, 300);

[Link]("Fade Transition Example");


[Link](scene);
[Link]();
}
public static void main(String[] args) {
launch(args);
}
}
Example: ScaleTransition Animation
import [Link]; import [Link];
import [Link]; import [Link]; import [Link];
import [Link]; import [Link]; import [Link];
public class ScaleTransitionExample extends Application {
@Override
public void start(Stage primaryStage) {
// Create a circle
Circle circle = new Circle(50, [Link]);
// Create a ScaleTransition
ScaleTransition scaleTransition = new ScaleTransition();
[Link](circle); // Set the node to animate (circle)
[Link](1.0); // Start scale on X-axis (100% of original size)
[Link](1.5); // End scale on X-axis (150% of original size)
[Link](1.0); // Start scale on Y-axis (100% of original size)
[Link](1.5); // End scale on Y-axis (150% of original size)
[Link]([Link]); // Repeat indefinitely
[Link](true); // Make it scale up and down
[Link]([Link](1)); // Set the duration of one cycle
[Link](); // Start the scale animation
StackPane root = new StackPane(); // Create a StackPane and add the circle
[Link]().add(circle);
Scene scene = new Scene(root, 400, 400); // Create the scene and add it to the stage
[Link]("ScaleTransition Example");
[Link](scene);
[Link]();
}
public static void main(String[] args) {
launch(args);
}
}
Advanced Features
• 3D Graphics:
– JavaFX supports basic 3D graphics with classes like Box, Sphere,
and Cylinder.
– Use Camera and Lighting for enhanced visual effects.
• Event Handling: Combine animations with mouse and
keyboard events for interactivity.
• Integration with Media: Add videos, sounds, and images
alongside animations.
Applications of JavaFX Graphics and
Animation
• Game development
• Interactive educational tools
• Data visualization
• Media players
• Simulation tools, etc.
Exercise
• Write a program demonstrating various aspects of
JavaFX:
– UI Controls: buttons, labels, text fields, sliders, etc.
– Layouts: VBox, HBox, and GridPane.
– Event Handlers: Button click events and slider value changes.
– Composite UI Controls: Custom control combining labels and text
fields.
– Properties and Bindings: Binding slider values to labels.
– CSS Styling: Applying styles to the UI components.
Sample Output
How to Connect Scene Builder with
IntelliJ IDEA
• Open IntelliJ IDEA settings and navigate to Languages
and Frameworks.
• Select JavaFX and specify the path to your Scene
Builder executable.
• Apply the changes and restart IntelliJ IDEA for settings
to take effect.

• Create a new FXML file in your IntelliJ IDEA project


structure.
• Right-click the FXML file and choose "Open in Scene
Builder."
• Design your user interface visually within Scene Builder.
Thank You!

You might also like