Chapter 3 - Java GUI Using JavaFX
Chapter 3 - Java GUI Using JavaFX
5
Cont…
10
JavaFX Architecture
11
Scene Graph
• The JavaFX scene graph is the starting point for constructing a JavaFX
application.
• It is a hierarchical tree of nodes that represents all of the visual elements of
the application's user interface. It can handle input and can be rendered.
• A single element in a scene graph is called a node. Each node has an ID,
style class, and bounding volume.
12
Cont…
• With the exception of the root node of a scene graph, each node in a scene
graph has a single parent and zero or more children. It can also have the
following:
o Effects, such as blurs and shadows
o Opacity
o Transforms
o Event handlers (such as mouse, key, and input method)
o An application-specific state
13
Cont…
• Unlike in the Swing and Abstract Window Toolkit (AWT), the JavaFX
scene graph also includes the graphics primitives, such as rectangles and
text, in addition to having controls, layout containers, images, and media.
• Animating various graphics in the scene graph can be accomplished
quickly using the [Link] APIs.
14
Cont…
2. Quantum Toolkit: ties Prism and Glass Windowing Toolkit together and
makes them available to the JavaFX layer above them in the stack.
• It also manages the threading rules related to rendering versus events
handling.
18
Glass Windowing Toolkit
• Glass Windowing Toolkit is the lowest level in the JavaFX graphics stack.
Its main responsibility is to provide native operating services, such as
managing the windows, timers, and surfaces.
• It serves as the platform-dependent layer that connects the JavaFX
platform to the native operating system.
• The Glass toolkit is also responsible for managing the event queue.
• unlike AWT, the Glass toolkit runs on the same thread as the JavaFX
application. In AWT, the native half of AWT runs on one thread and the
19
Java level runs on another thread.
Threads
• The system runs two or more of the following threads at any given time.
o JavaFX application thread: This is the primary thread used by
JavaFX application developers.
o Prism render thread: This thread handles the rendering separately
from the event dispatcher.
o Media thread: This thread runs in the background and synchronizes the
latest frames through the scene graph by using the JavaFX application
thread.
20
Media and Images
21
Web Component
22
Cont…
24
3.2. JavaFX layout components
• Layout containers or panes can be used to allow for flexible and dynamic
arrangements of the UI controls within a scene graph of a JavaFX
application.
• The JavaFX Layout API includes the following container classes that
automate common layout models:
o The BorderPane class lays out its content nodes in the top, bottom,
right, left, or center region.
o The HBox class arranges its content nodes horizontally in a single row.
o The VBox class arranges its content nodes vertically in a single column.25
Cont…
26
Cont…
o The TilePane class places its content nodes in uniformly sized layout
cells or tiles
o The AnchorPane class enables developers to create anchor nodes to the
top, bottom, left side, or center of the layout.
• To achieve a desired layout structure, different containers can be nested
within a JavaFX application.
• [Link] package is used to add Layout containers or panes.
27
3.3.1. Event handling
28
Types of Events
• The events can be broadly classified into the following two categories −
1. Foreground Events − Those events which require the direct interaction
of a user.
o They are generated as consequences of a person interacting with the
graphical components in a Graphical User Interface.
o For example, clicking on a button, moving the mouse, entering a
character through a keyboard, selecting an item from the list, scrolling
the page, etc.
29
Cont…
30
Cont…
ii. Key Event: This is an input event that indicates the keystroke occurred
on a node. It is represented by the class named KeyEvent. This event
includes actions like key pressed, key released and key typed.
iii. Drag Event: This is an input event that occurs when the mouse is
dragged. It is represented by the class named DragEvent. It includes drag
entered, drag dropped, drag entered target, drag exited target, drag over,
etc.
32
Cont…
33
Event Handling
• 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.
• In JavaFX every event has 3 basic elements:
1. Target: the node on which an event occurred. A target can be a
window, scene, and a node.
2. 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.
34
Cont…
3. Type: the type of the occurred event; in the case of mouse event –
mouse pressed, mouse released are the type of events.
• To register a handler, use the addEventHandler() method. This method
takes the event type and the handler as arguments.
• When you no longer want an event handler to process events for a node or
for an event type, remove the handler using the removeEventHandler()
method. This method also takes the event type and the handler as
arguments.
35
Example: Register an event using addEventHandler() method
public class MyApplication extends Application {
@Override public void start(Stage primaryStage) throws Exception {
// Create a button
Button button = new Button("Click me!");
// Set an event handler for the button using addEventHandler()
[Link](MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()
{
@Override public void handle(MouseEvent event) {
[Link]("Button clicked!"); } });
cont…
36
Cont…
// Add the button to a layout pane
StackPane root = new StackPane();
[Link]().add(button);
// Create a scene and add it to the stage
Scene scene = new Scene(root, 300, 250);
[Link](scene);
// Show the stage
[Link]();
}
public static void main(String[] args) {
launch(args);
}
37
}
Cont…
In above example, we create a Button and set an event handler for it using the
addEventHandler() method.
• The event handler is an anonymous inner class that implements the
EventHandler interface and simply prints a message to the console when
the button is clicked.
• We then add the button to a StackPane, create a Scene with the StackPane
as its root node, and add the scene to a Stage. Finally, we show the stage
using the show method.
38
Example2: Removing an event using removeEventHandler() method
public class MyApplication extends Application {
private EventHandler<MouseEvent> buttonClickHandler;
@Override
public void start(Stage primaryStage) throws Exception {
// Create a button
Button button = new Button("Click me!");
// Set an event handler for the button using addEventHandler()
buttonClickHandler = event -> {
[Link]("Button clicked!");
}; cont… 39
Cont…
[Link](MouseEvent.MOUSE_CLICKED, buttonClickHandler);
// Remove the event handler using removeEventHandler()
[Link](MouseEvent.MOUSE_CLICKED, buttonClickHandler);
[Link]("Event handler removed.");
• In this example, we create a Button and set an event handler for it using the
addEventHandler() method.
• The event handler is a lambda expression that simply prints a message to the console
when the button is clicked.
• Then the event handler will be removed from the button using the
removeEventHandler() method. 40
3.3.2. Basic UI controls
6. RadioButton: A control for allowing users to select one option from a list.
7. ComboBox: A control for allowing users to select one option from a drop-
down list.
8. ListView: A control for displaying a list of items that can be selected.
9. TableView: A control for displaying tabular data.
10. TreeView: A control for displaying hierarchical data.
11. MenuBar: A control for displaying menus and menu items.
12. ToolBar: A control for displaying buttons and other controls in a
horizontal or vertical bar. 42
Cont…
43
Cont…
• Using the JavaFX library, you can draw predefined shapes such as Line,
Rectangle, Circle, Ellipse, Polygon, Polyline, Cubic Curve, Quad Curve,
Arc.
• You can also draw path elements such as MoveTO Path Element, Line,
Horizontal Line, Vertical Line, Cubic Curve, Quadratic Curve, Arc.
• In addition to these, you can also draw a 2D shape by parsing SVG path.
48
3.5.1. Color, Texts, Fonts
• in JavaFX, you can use the [Link] class to create text-
based information on the interface of your JavaFX application.
• This class provides various methods to alter various properties of the
text.
• To set the font, you can use an instance of the [Link]
class. The [Link]() method enables you to specify the font family
name and size.
49
Cont…
52
Cont…
• JavaFX CSS uses the same CSS syntax as CSS for the web, but the CSS
properties are specific to JavaFX and therefore have slightly different
names than their web counterparts.
• For example, all JavaFX property names have been prefixed with a
vendor extension of -fx-.
56
CSS Selectors
• A selector is an HTML tag at which a style will be applied.
• Selectors naming conventions :
1. If the style class selector consists of more than one word, use the hyphen
between them.
2. Style class selector names are preceded by a dot(.)
3. the style for a particular node can be defined by using the node's ID, Use
the # symbol before the Node_ID to make a style name for that node
57
Cont…
.root
{
Applying font-family and
-fx-font-family : "serief";
background to all scene graph
-fx-background : rgb(225,227,2255);
}
58
Examples
.button {
Applying background-color and text-
-fx-background-color: red; fill properties to all button classes
-fx-text-fill: white;
}
#displayLabel1{
-fx-background-color : rgb(123,126,227); Applying background-color ,
-fx-padding : 5; padding, and text-fill properties
to the label node whose node-id
-fx-text-fill : rgb(245,123,201);
is displayLabel1
}
59
Applying CSS styling
• To apply a CSS stylesheet to a JavaFX application, you can create a new
CSS file and save it in the same directory as the main class of your
application.
• The stylesheet you create must have an extension of .css. After creating
the stylesheet, you can add it to a Scene object using the
getStylesheets().add() method.
Example:
Scene scene = new Scene(new Group(), 500, 400);
[Link]().add("path/[Link]"); 60
3.6. Properties and Bindings
61
Cont…
63
3.7. Graphics and Animation
• JavaFX provides a rich set of graphics and animation APIs that allow
developers to create visually appealing and interactive applications.
• The [Link] package contains classes that can be used to
animate nodes by changing their properties over time.
• You can use JavaFX to quickly develop applications with rich user
experiences, create animated objects and attain complex effects with very
little coding.
64
Cont…
65
Common animation techniques in JavaFX
66
Cont…
69