0% found this document useful (0 votes)
0 views38 pages

Unit 6 - GUI With JavaFX

JavaFX is a Java library for creating desktop and Rich Internet Applications, featuring advanced graphics, UI controls, and multimedia support. Initially introduced in 2007 and integrated with the JDK in 2011, it serves as an alternative to Swing, offering a more modern approach to UI development. Key components include the Scene Graph, FXML for UI layout, and various node types for building responsive applications.

Uploaded by

living soul
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)
0 views38 pages

Unit 6 - GUI With JavaFX

JavaFX is a Java library for creating desktop and Rich Internet Applications, featuring advanced graphics, UI controls, and multimedia support. Initially introduced in 2007 and integrated with the JDK in 2011, it serves as an alternative to Swing, offering a more modern approach to UI development. Key components include the Scene Graph, FXML for UI layout, and various node types for building responsive applications.

Uploaded by

living soul
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
You are on page 1/ 38

Introduction

JavaFX is a Java library for developing desktop applications and Rich Internet
Applications (RIA).
It offers features like 2D/3D shapes, effects, animations, layouts, UI controls, media
integration, and more. JavaFX is designed as an alternative to Swing, providing more
advanced features, flexible layouts, and hardware acceleration.
It is lightweight, OS-independent, and supports Windows, Linux, and macOS.

History of JavaFX
JavaFX was initially created by Chris Oliver as "Form Follows Function" (F3).
Sun Microsystems acquired the project in 2005 and officially introduced it as
JavaFX at the JavaOne conference in 2007.
JavaFX 1.0 was released in December 2008. After Oracle acquired Sun
Microsystems in 2010, JavaFX 2.0 was launched in 2011, marking its integration
with the JDK and phasing out the earlier JavaFX 1.x versions.

JavaFX as a Swing Replacement


While JavaFX was initially intended to replace Swing for Java desktop applications,
Swing is still supported and maintained. JavaFX is an alternative, but not a strict
replacement.

What does the 'FX' in 'JavaFX' stand for?


Most likely it stands for Java "special EFF-ECTS" as FX is normally the
abbreviation given to special effects mostly sound or visual.
Features of JavaFX
Java Library: It is a Java library which consists of many classes and interfaces that
are written in Java.
Scene Graph: The core concept of JavaFX is the Scene Graph, which is a
hierarchical tree of nodes that represents all graphical elements in a scene. A node
can be a UI control, image, shape, or even a container that holds other nodes.
FXML: FXML is the XML based Declarative mark up language. The coding can be
done in FXML to provide the more enhanced GUI to the user.
Scene Builder: Scene Builder generates FXML mark-up which can be ported to an
IDE.
Web view: Web pages can be embedded with JavaFX applications. Web View uses
WebKitHTML technology to embed web pages.
Built in UI controls: JavaFX contains Built-in components which are not dependent
on operating system. The UI component are just enough to develop a full featured
application.
CSS styling: JavaFX code can be embedded with the CSS to improve the style of
the application. We can enhance the view of our application with the simple
knowledge of CSS.
Swing interoperability: The JavaFX applications can be embedded with swing code
using the Swing Node class. We can update the existing swing application with the
powerful features of JavaFX.
Canvas API: Canvas API provides the methods for drawing directly in an area of a
JavaFX scene.
Rich Set of APIs: JavaFX provides a rich set of API's to develop GUI applications.
Integrated Graphics Library: An integrated set of classes are provided to deal with
2D and 3D graphics.
Graphics Pipeline: JavaFX graphics are based on Graphics rendered
pipeline(prism). It offers smooth graphics which are hardware accelerated.
High Performance Media Engine: The media pipeline supports the playback of
web multimedia on a low latency. It is based on a Gstreamer Multimedia framework.
Animations and Effects: JavaFX offers built-in support for animations and visual
effects. These features are useful for making your applications more interactive and
dynamic, with transitions, fades, and other visual effects.
Self-contained application deployment model: Self Contained application packages
have all of the application resources and a private copy of Java and JavaFX Runtime.
Event Handling: JavaFX uses an event-driven programming model, meaning that
user interactions like button clicks, text input, and mouse movements trigger events
that can be handled by the application logic.
Responsive Layouts: JavaFX provides various layout panes like HBox, VBox,
GridPane, and AnchorPane, which make it easy to design responsive and flexible
UIs.
Multimedia Support: JavaFX includes APIs for incorporating audio, video, and
images into your applications, making it suitable for creating rich multimedia
applications.
Basic Structure of a JavaFX Application:
A simple JavaFX application has three main components:

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


2. Scene – The content inside the window, containing a scene graph.
3. Nodes – Elements in the scene graph (controls, shapes, images).

In JavaFX, a Scene represents the visual content of a JavaFX application window,


or Stage.
It serves as a container that holds all the UI elements, or Nodes, such as buttons, text
fields, and images.
The class Scene of the package javafx.scene represents the scene object. You can
create a scene by instantiating the Scene Class.
A `Stage` (window) can display exactly one `Scene` at a time, and each `Scene`
consists of a hierarchy of nodes that make up the graphical user interface (GUI).

JavaFX Stage Overview


A Stage in JavaFX represents a window that contains the entire JavaFX application's
content.

It can be thought of as the top-level container for the application's graphical


interface.

The Stage is a part of the javafx.stage package and is the foundation upon which all
JavaFX applications are built.

Primary Stage
 The primary stage is created automatically by the JavaFX platform when the
application starts.
 The primary stage object is passed to the start(Stage primaryStage) method,
which is defined in the Application class. This is where you define the UI
elements and properties of your stage.

Stage Properties
 Width and Height: The size of the window can be set using setWidth() and
setHeight() methods or directly in the Stage constructor.
 Content Area: This is where all UI controls and layouts are placed.
 Decorations: The decorations refer to the title bar, borders, and window
controls like close, maximize, and minimize buttons. You can customize these
decorations or even remove them if needed.

Displaying the Stage


 The stage is not visible by default. To display the stage, you must call the
show() method:

primaryStage.show();
Types of Stages
There are five types of stages in JavaFX, each with different appearance properties:

1. Decorated Stage:
o A stage with a default window border, title bar, and control buttons
(close, maximize, minimize).
o This is the default stage type.
o Example:

primaryStage.initStyle(StageStyle.DECORATED);

2. Undecorated Stage:
o A stage without the window decorations (no title bar, no borders, no
control buttons).
o Often used for custom windows.
o Example:

primaryStage.initStyle(StageStyle.UNDECORATED);

3. Transparent Stage:
o The stage has no background, borders, or decorations, making it fully
transparent.
o The content of the stage itself is rendered without a background.
o Example:

primaryStage.initStyle(StageStyle.TRANSPARENT);

4. Unified Stage:
o A unified stage where the window's content area blends with the
window's borders. This gives the appearance of a seamless design.
o Example:

primaryStage.initStyle(StageStyle.UNIFIED);

5. Utility Stage:
o A small utility window, typically without minimize or maximize
buttons.
o Useful for pop-ups or small tool windows.
o Example:
primaryStage.initStyle(StageStyle.UTILITY);

Basic Example
Here's a simple example that creates a JavaFX application with a decorated stage:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.scene.layout.StackPane;

public class JavaFXStageExample extends Application {

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX Stage Example");

// Set width and height


primaryStage.setWidth(400);
primaryStage.setHeight(300);

// Create a label
Label label = new Label("Hello, Stage!");

// Set up the layout and scene


StackPane root = new StackPane();
root.getChildren().add(label);
Scene scene = new Scene(root);

// Set the scene on the stage


primaryStage.setScene(scene);

// Display the stage


primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}

Additional Features of a Stage:

 Resizable: You can control whether the stage is resizable by calling


primaryStage.setResizable(false).
 FullScreen: Use primaryStage.setFullScreen(true) to enable full-screen
mode.
 Modality: For secondary stages (new windows), you can set their modality
using primaryStage.initModality(Modality.WINDOW_MODAL) to block
interactions with the parent window.

This covers the basics of creating and managing stages in JavaFX!

Key Concepts of a Scene

Scene Graph:
The scene is built using a Scene Graph, which is a tree-like structure where each
graphical element (called a Node) is a part of this graph. The root node is the topmost
parent, and all other elements are its children or nested child nodes. The scene graph
ensures efficient rendering, event handling, and layout management.

Root Node:
A `Scene` is created with a root node, which is usually a container (like a `Pane`,
`HBox`, `VBox`, or `BorderPane`) that holds other nodes (e.g., buttons, labels, and
other UI elements). Every other element in the scene is added as a child of this root
node.
Dimensions:
When you create a `Scene`, you specify its width and height in pixels. This size
defines how large the visual window will be within the `Stage`.

Switching Scenes:
A `Stage` can only have one active `Scene` at a time, but you can easily swap out
scenes to show different content in the same window. This is useful when managing
complex applications that need to switch between different views (e.g., from a login
screen to a dashboard).

Creating a Scene:
You can create a `Scene` by passing a root node and dimensions (width and height)
to the `Scene` constructor. Here's a basic example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class SceneExample extends Application {

@Override
public void start(Stage primaryStage) {
// Create a button node
Button button = new Button("Click Me!");
// Create a layout (root node)
StackPane root = new StackPane();
root.getChildren().add(button); // Add the button to the layout

// Create a Scene with the root node and dimensions


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

// Set the scene on the Stage


primaryStage.setScene(scene);
primaryStage.setTitle("JavaFX Scene Example");

// Show the Stage


primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}
Key Concepts of Nodes
In JavaFX, nodes are the fundamental building blocks of the Scene Graph, and they
represent all visual elements that can appear in a user interface. These nodes are
divided into different categories based on their role in the scene graph:

1. Root Node:
 The Root Node is the top-most node in the scene graph and serves as the
container for all other nodes within a scene.
 Typically, root nodes are layout containers, such as VBox, HBox, GridPane,
StackPane, or Group, that hold other nodes (branch or leaf nodes).
 Every scene requires a root node to be passed to it. The entire layout of the
scene graph is built under the root node.
 Example of root node:

StackPane root = new StackPane();


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

2. Branch Nodes (Parent Nodes):


 Branch Nodes, also known as Parent Nodes, are nodes that can have child
nodes. These nodes are containers that manage and arrange their children.
 The Parent class from javafx.scene is the base class for all branch nodes. A
branch node can contain other nodes (either branch or leaf nodes).
 Common examples of branch nodes include layout containers like VBox,
HBox, GridPane, BorderPane, and Group.

Types of Branch Nodes:

 Group: A Group node is a container that holds a list of children. Any


transformation or effect applied to the group is applied to all its children.
o Example:

Group group = new Group();


group.getChildren().addAll(node1, node2);
 Region: The Region class is the base class for all UI controls, layout panes,
and chart components. A Region can have child nodes and provides more
advanced layout capabilities like handling size and alignment.
 WebView: The WebView node is a specialized container that displays web
content and manages a web engine.

Key Characteristics of Branch Nodes:

 Branch nodes manage the positioning, layout, and rendering of their child
nodes.
 Any transformation (like scaling, rotating) applied to a branch node affects all
its children.
 Layout panes (HBox, VBox, GridPane, etc.) are typical branch nodes that
organize child nodes in specific arrangements.

3. Leaf Nodes:
 Leaf Nodes are nodes that cannot have children. They represent individual
UI components or graphical shapes in the scene graph.
 Leaf nodes include standard UI controls like buttons, labels, and text fields,
as well as 2D and 3D shapes, media components, and other graphical
elements.

Examples of Leaf Nodes:

 UI Controls: Button, Label, TextField, TextArea, CheckBox, ChoiceBox,


etc.
o Example:

Button button = new Button("Click Me");

 Geometrical Shapes: Circle, Rectangle, Polygon, Ellipse, etc. These nodes


are often used to draw basic shapes and graphical elements in the scene.
o Example:

Circle circle = new Circle(50, 50, 40); // Creates a circle at (50,50) with
a radius of 40
 3D Objects: Shapes like Box, Cylinder, and Sphere represent 3D geometrical
objects.
 Media Elements: Nodes like ImageView for displaying images, MediaView
for displaying videos, and other media-related objects.

Key Node Types and Their Usage:


 Graphical Objects (2D and 3D): These include shapes like Rectangle,
Circle, Polygon, and 3D objects like Box and Sphere. They can be used to
represent simple or complex graphical scenes.
 UI Controls: These are nodes that represent various controls such as buttons,
checkboxes, text fields, etc. They are essential for creating interactive user
interfaces.
 Containers (Layout Panes): Layout panes such as BorderPane, GridPane,
FlowPane, and StackPane are specialized branch nodes used to arrange and
manage child nodes in a specific layout.
 Media Elements: Nodes such as ImageView (for displaying images),
MediaView (for displaying video or audio), and others fall into this category.

Important Node Class:


 Node Class: The Node class (in the javafx.scene package) is the base class
for all JavaFX elements, both branch and leaf nodes. It defines common
properties and behaviors, such as layout bounds, transformations, effects, and
event handling, that all nodes share.

Root Node and Scene Relationship:


 When a scene is created, a root node must be passed to the Scene constructor.
 If a Group is used as the root node, all nodes within the group will be clipped
to the scene, meaning the size of the scene defines how much of the nodes are
visible. Additionally, if the size of the scene changes, the layout of the scene
graph will not be affected unless layout containers are used.
Example Structure of a Scene Graph:

Scene
├── Root Node (e.g., VBox)
├── Branch Node (e.g., HBox)
│ ├── Leaf Node (Button)
│ ├── Leaf Node (Label)
├── Leaf Node (Circle)

This example shows a VBox as the root node containing an HBox (a branch node)
and a Circle (a leaf node). The HBox contains two child nodes: a Button and a Label.

Event Handling:
Each node in the scene graph can handle events (like clicks, key presses, mouse
movements) using JavaFX’s event-driven model. Event handlers can be attached to
nodes, and these events propagate through the scene graph.

Styling with CSS:


You can apply CSS to style the nodes inside the scene. JavaFX supports external
CSS files, allowing you to separate the styling from the logic. This makes it easy to
customize the appearance of the application.

Switching Between Scenes:


In a JavaFX application, you can switch between different scenes by creating new
`Scene` objects and setting them on the `Stage`. For example:
Scene scene1 = new Scene(root1, 400, 300);
Scene scene2 = new Scene(root2, 400, 300);

// Switch scenes on button click


button.setOnAction(event -> primaryStage.setScene(scene2));

Summary:
- A Scene is the container for all visual content in a JavaFX application.
- It holds a Scene Graph, which is a tree of nodes where each node represents a
graphical element (e.g., buttons, labels).
- A Root Node is the top-level node in the scene, and it usually holds child nodes
that make up the user interface.
- You can apply CSS to a scene for styling and can easily switch between scenes
within the same stage.

JavaFX vs Swing

Feature JavaFX Swing

Introduced in Java 8, modern GUI Older GUI toolkit, part of the


Introduction
toolkit. JDK since Java 1.2.

Platform JavaFX is a software platform Swing is just a suite of APIs

Supports advanced 2D/3D


Graphics & Basic 2D graphics, no built-in
graphics, animation, and effects
Animation animation support.
out of the box.

Styling is limited, must use


Uses CSS-like stylesheets (JavaFX
Styling Java code or third-party
CSS) for styling UI components.
libraries.

Supports FXML, a declarative way No built-in declarative UI


Declarative UI
to define UIs. support.
Feature JavaFX Swing

Relies on older and


More flexible and modern layout
Layout System sometimes more complex
system.
layout managers.

Built-in support for embedding Requires third-party libraries


Media Support
media (audio, video). for media support.

Uses a modern, simple single- Uses the Event Dispatch


Threading
threaded event loop with Thread (EDT) for all GUI
Model
Platform.runLater() for UI updates. updates.

Event Simpler and more consistent event Event handling can be more
Handling handling model. verbose and complex.

Hardware Supports GPU acceleration for No direct support for


Acceleration better performance in rendering. hardware acceleration.

Platform-independent, but with Platform-dependent look and


Look and Feel modern, customizable looks via feel, can use LookAndFeel
CSS. classes.

Swing components can


Responsive JavaFX components adapt more
struggle with responsive
Design naturally to different screen sizes.
design.

Drag-and- Built-in drag-and-drop support is More complex to implement


Drop Support easier to implement. drag-and-drop functionality.

Easier for beginners with support


Ease of Steeper learning curve due to
for modern UI paradigms like CSS
Learning older design principles.
and FXML.

Long-Term JavaFX is actively developed and Swing is no longer actively


Support maintained as a part of OpenJFX. developed, considered legacy.
Feature JavaFX Swing

Suited for legacy


Best suited for modern
applications, simpler UIs, or
Use Case applications with complex UI,
when backward compatibility
animations, and media.
is needed.

Large but aging community,


Community Growing and active community,
many developers have moved
Support with more focus in recent years.
on to newer toolkits.

Swing predates the modular


JavaFX is modular, can be used in
Modularity system, but can still be used in
Java's modular system (Java 9+).
modular projects with effort.

Touch and Native support for touch, multi- No built-in support for touch
Multi-touch touch, and gesture recognition. or gestures.

Supports FXML, an XML-based


FXML No equivalent XML-based UI
language to build UIs outside of
Support declaration.
Java code.

Summary

 JavaFX is more modern, versatile, and better suited for today's GUI
development needs, especially for applications requiring rich UIs,
multimedia, and scalability.
 Swing is still functional and appropriate for maintaining older applications
but lacks the modern capabilities and ease of use that JavaFX provides.
JavaFX Layouts

A JavaFX application can manually lay out the UI by setting the position and size
properties for each UI element.
This can be done by setting the position (using properties like setLayoutX() and
setLayoutY()) and the size (using setPrefWidth(), setPrefHeight(), setMinWidth(),
setMaxHeight(), etc.) for each individual UI element.

Here’s a brief example of how you can manually lay out UI components:

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.Pane;

import javafx.stage.Stage;

public class ManualLayoutExample extends Application {

@Override

public void start(Stage primaryStage) {

// Create a button

Button button = new Button("Click Me");

// Set button position

button.setLayoutX(100); // x position
button.setLayoutY(150); // y position

// Set button size

button.setPrefWidth(150);

button.setPrefHeight(50);

// Create a pane and add the button to it

Pane pane = new Pane();

pane.getChildren().add(button);

// Set up the scene and stage

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

primaryStage.setScene(scene);

primaryStage.setTitle("Manual Layout Example");

primaryStage.show();

public static void main(String[] args) {

launch(args);

}
This approach gives you pixel-perfect control, but for dynamic layouts or resizing,
JavaFX's layout managers (like VBox, HBox, GridPane, etc.) are usually more
flexible.

An easier option is to make use of layout panes

Using Built-in Layout Panes


The layout container classes, called panes, are available with the JavaFX SDK
Use layout panes to easily manage the user interface for your JavaFX application

The JavaFX SDK provides several layout panes for the easy setup and management
of classic layouts such as rows, columns, stacks, tiles, and others
As a window is resized, the layout pane automatically repositions and resizes the
nodes that it contains according to the properties for the nodes

FlowPane
The nodes within a FlowPane layout pane are laid out consecutively and wrap at the
boundary set for the pane
Nodes can flow vertically (in columns) or horizontally (in rows)
A vertical flow pane wraps at the height boundary for the pane
A horizontal flow pane wraps at the width boundary for the pane
Figure 1-10 shows a sample horizontal flow pane using numbered icons
By contrast, in a vertical flow pane, column one would contain pages one through
four and column two would contain pages five through eight
Description of "Figure 1-10 Sample Horizontal Flow Pane"
Gap properties can be set to manage the spacing between the rows and columns
The padding property can be set to manage the distance between the nodes and the
edges of the pane
Example 1-6 creates a horizontal flow pane for a series of page icons.
Usage: Useful for dynamically sized content or creating a toolbar.

FlowPane flowPane = new FlowPane();


flowPane.getChildren().addAll(new Button("Button 1"), new Button("Button 2"));

BorderPane
The BorderPane layout pane provides five regions in which to place nodes: top,
bottom, left, right, and center
The regions can be any size
If your application does not need one of the regions, you do not need to define it and
no space is allocated for it
A border pane is useful for the classic look of a tool bar at the top, a status bar at the
bottom, a navigation panel on the left, additional information on the right, and a
working area in the center
If the window is larger than the space needed for the contents of each region, the
extra space is given to the center region by default
If the window is smaller than the space needed for the contents of each region, the
regions might overlap
The overlap is determined by the order in which the regions are set
For example, if the regions are set in the order of left, bottom, and right, when the
window is made smaller, the bottom region overlaps the left region and the right
region overlaps the bottom region
If set in the order of left, right, and bottom, when the window is made smaller, the
bottom region overlaps both the left and right regions
Example 1-1 shows the code for creating the border pane that is used for the UI that
is built by the Layout Sample application. The methods that create the layout panes
used in each region are described in the remaining sections of this topic
Note that the bottom region of the border pane is not used in this sample. If you want
to add something to the bottom region, use the following statement and replace node
with the control of your choice:
border.setBottom(node);
The setRight() method in Example 1-1 adds the flow pane to the right region of the
border pane.
The setCenter() method in Example 1-1 adds the grid pane to the center region of
the border pane.

Usage: Ideal for applications with a fixed layout structure like a standard web page.

BorderPane borderPane = new BorderPane();


borderPane.setTop(new Label("Top"));
borderPane.setBottom(new Label("Bottom"));
borderPane.setLeft(new Label("Left"));
borderPane.setRight(new Label("Right"));
borderPane.setCenter(new Label("Center"));

HBox
The HBox layout pane provides an easy way for arranging a series of nodes in a
single row
Figure 1-2 shows an example of an HBox pane
The padding property can be set to manage the distance between the nodes and the
edges of the HBox pane
Spacing can be set to manage the distance between the nodes
The style can be set to change the background color
Example 1-2 creates an HBox pane for a tool bar that contains two buttons.
Usage: Suitable for horizontal alignment of controls or components.
HBox hBox = new HBox();
hBox.getChildren().addAll(new Button("Button 1"), new Button("Button 2"));

VBox
Arranges children in a vertical column.
Usage: Useful for vertical alignment of controls or components.
Code Example:
VBox vBox = new VBox();
vBox.getChildren().addAll(new Button("Button 1"), new Button("Button 2"));

Grid Pane
The GridPane layout pane enables you to create a flexible grid of rows and columns
in which to lay out nodes
Arranges children in a grid of rows and columns.
Nodes can be placed in any cell in the grid and can span cells as needed
A grid pane is useful for creating forms or any layout that is organized in rows and
columns
Figure 1-8 shows a grid pane that contains an icon, title, subtitle, text and a pie chart
In this figure, the gridLinesVisible property is set to display grid lines, which show
the rows and columns and the gaps between the rows and columns
This property is useful for visually debugging your GridPane layouts.
Usage: Best for complex layouts where precise positioning is required.
Description of "Figure 1-8 Sample Grid Pane"
Gap properties can be set to manage the spacing between the rows and columns
The padding property can be set to manage the distance between the nodes and the
edges of the grid pane
The vertical and horizontal alignment properties can be set to manage the alignment
of individual controls in a cell

Example 1-5 creates the grid pane shown in Figure 1-8


Create a Grid Pane
public GridPane addGridPane() {
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(0, 10, 0, 10));

// Category in column 2, row 1


Text category = new Text("Sales:");
category.setFont(Font.font("Arial", FontWeight.BOLD, 20));
grid.add(category, 1, 0);
// Title in column 3, row 1
Text chartTitle = new Text("Current Year");
chartTitle.setFont(Font.font("Arial", FontWeight.BOLD, 20));
grid.add(chartTitle, 2, 0);

// Subtitle in columns 2-3, row 2


Text chartSubtitle = new Text("Goods and Services");
grid.add(chartSubtitle, 1, 1, 2, 1);

// House icon in column 1, rows 1-2


ImageView imageHouse = new ImageView(
new
Image(LayoutSample.class.getResourceAsStream("graphics/house.png")));
grid.add(imageHouse, 0, 0, 1, 2);

// Left label in column 1 (bottom), row 3


Text goodsPercent = new Text("Goods\n80%");
GridPane.setValignment(goodsPercent, VPos.BOTTOM);
grid.add(goodsPercent, 0, 2);

// Chart in columns 2-3, row 3


ImageView imageChart = new ImageView(
new
Image(LayoutSample.class.getResourceAsStream("graphics/piechart.png")));
grid.add(imageChart, 1, 2, 2, 1);
// Right label in column 4 (top), row 3
Text servicesPercent = new Text("Services\n20%");
GridPane.setValignment(servicesPercent, VPos.TOP);
grid.add(servicesPercent, 3, 2);

return grid;
}

Code Example:
GridPane gridPane = new GridPane();
gridPane.add(new Label("Name:"), 0, 0);
gridPane.add(new TextField(), 1, 0);

Go to the following link for full description of JavaFX Layouts:


https://docs.oracle.com/javafx/2/layout/builtin_layouts.htm
JavaFX UI Controls
Module javafx.controls: Defines the UI controls, charts, and skins that are available
for the JavaFX UI toolkit
Module Graph:

Label
Label is a non-editable text control.
A Label is useful for displaying text that is required to fit within a specific space,
and thus may need to use an ellipsis or truncation to size the string to fit.
Labels also are useful in that they can have mnemonics which, if used, will send
focus to the Control listed as the target of the labelFor property.
Label sets focusTraversable to false.
Example:
Label label = new Label("a label");
Since:
JavaFX 2.0
TextField
Text input component that allows a user to enter a single line of unformatted text.
Unlike in previous releases of JavaFX, support for multi-line input is not available
as part of the TextField control, however this is the sole-purpose of the TextArea
control.
Additionally, if you want a form of rich-text editing, there is also the HTMLEditor
control.
TextField supports the notion of showing prompt text to the user when there is no
text already in the TextField (either via the user, or set programmatically). This is a
useful way of informing the user as to what is expected in the text field, without
having to resort to tooltips or on-screen labels.

TextField textField = new TextField();


textField.setPromptText("Enter text here");

Button
public class Button
extends ButtonBase
A simple button control.
The button control can contain text and/or a graphic.
A button control has three different modes:
Normal: A normal push button.
Default: A default Button is the button that receives a keyboard VK_ENTER press,
if no other node in the scene consumes it.
Cancel: A Cancel Button is the button that receives a keyboard VK_ESC press, if
no other node in the scene consumes it.
When a button is pressed and released a ActionEvent is sent. Your application can
perform some action based on this event by implementing an EventHandler to
process the ActionEvent. Buttons can also respond to mouse events by implementing
an EventHandler to process the MouseEvent
MnemonicParsing is enabled by default for Button.
Example:
Button button = new Button("Click Me");
button.setOnAction(e -> System.out.println("Button clicked!"));

RadioButton
public class RadioButton
extends ToggleButton
RadioButtons create a series of items where only one item can be selected.
RadioButtons are a specialized ToggleButton.
When a RadioButton is pressed and released a ActionEvent is sent.
Your application can perform some action based on this event by implementing an
EventHandler to process the ActionEvent.
Only one RadioButton can be selected when placed in a ToggleGroup.
Clicking on a selected RadioButton will have no effect.
A RadioButton that is not in a ToggleGroup can be selected and unselected.
By default a RadioButton is not in a ToggleGroup. Calling
ToggleGroup.getSelectedToggle() will return you the RadioButton that has been
selected.
ToggleGroup group = new ToggleGroup();
RadioButton button1 = new RadioButton("select first");
button1.setToggleGroup(group);
button1.setSelected(true);
RadioButton button2 = new RadioButton("select second");
button2.setToggleGroup(group);

CheckBox
public class CheckBox
extends ButtonBase

The `CheckBox` class extends `ButtonBase` and supports tri-state selection. A


`CheckBox` can be in one of three states:

1. Checked: `indeterminate == false`, `selected == true`


The CheckBox is rendered with a checkmark or tick.

2. Unchecked: `indeterminate == false`, `selected == false`


The CheckBox is empty (not checked).

3. Indeterminate: `indeterminate == true`


The CheckBox is rendered with a dash or minus sign, indicating an undefined or
mixed state.

In JavaFX:
- A CheckBox is checked when `selected` is `true` and `indeterminate` is `false`.
- A CheckBox is unchecked when `selected` is `false` and `indeterminate` is `false`.
- A CheckBox is indeterminate when `indeterminate` is `true`, regardless of
`selected`.

The `allowIndeterminate` property controls whether the CheckBox can enter the
indeterminate state:

- If `allowIndeterminate` is `true`, the CheckBox can switch to the indeterminate


state.
- If `allowIndeterminate` is `false`, the CheckBox can only be checked or unchecked.

Example:
CheckBox cb = new CheckBox("a checkbox");
cb.setIndeterminate(false);

In this example, the CheckBox `cb` is created and set to not be indeterminate.

HyperLink
public class Hyperlink
extends ButtonBase

A clickable link that can open a URL.


An HTML like label which can be a graphic and/or text which responds to rollovers
and clicks. When a hyperlink is clicked/pressed isVisited() becomes true. A
Hyperlink behaves just like a Button. When a hyperlink is pressed and released a
ActionEvent is sent, and your application can perform some action based on this
event.

Example:
Hyperlink link = new Hyperlink("www.oracle.com");

Menu
@DefaultProperty(value="items")
public class Menu
extends MenuItem

A menu with menu items.


A popup menu of actionable items which is displayed to the user only upon request.
When a menu is visible, in most use cases, the user can select one menu item before
the menu goes back to its hidden state. This means the menu is a good place to put
important functionality that does not necessarily need to be visible at all times to the
user.
Menus are typically placed in a MenuBar, or as a submenu of another Menu. If the
intention is to offer a context menu when the user right-clicks in a certain area of
their user interface, then this is the wrong control to use. This is because when Menu
is added to the scenegraph, it has a visual representation that will result in it
appearing on screen. Instead, ContextMenu should be used in this circumstance.
Creating a Menu and inserting it into a MenuBar is easy, as shown below:
final Menu menu1 = new Menu("File");
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(menu1);
A Menu is a subclass of MenuItem which means that it can be inserted into a Menu's
items ObservableList, resulting in a submenu being created:
MenuItem menu12 = new MenuItem("Open");
menu1.getItems().add(menu12);

The items ObservableList allows for any MenuItem type to be inserted, including its
subclasses Menu, MenuItem, RadioMenuItem, CheckMenuItem, CustomMenuItem
and SeparatorMenuItem. In order to insert an arbitrary Node to a Menu, a
CustomMenuItem can be used. One exception to this general rule is that
SeparatorMenuItem could be used for inserting a separator.

Menu menu = new Menu("File");


MenuItem menuItem = new MenuItem("Open");
menu.getItems().add(menuItem);
MenuBar menuBar = new MenuBar(menu);

Tooltip
@IDProperty(value="id")
public class Tooltip
extends PopupControl
Provides additional information when hovering over a control.
Tooltips are common UI elements which are typically used for showing additional
information about a Node in the scenegraph when the Node is hovered over by the
mouse. Any Node can show a tooltip. In most cases a Tooltip is created and its text
property is modified to show plain text to the user. However, a Tooltip is able to
show within it an arbitrary scenegraph of nodes - this is done by creating the
scenegraph and setting it inside the Tooltip graphic property.
You use the following approach to set a Tooltip on any node:
Rectangle rect = new Rectangle(0, 0, 100, 100);
Tooltip t = new Tooltip("A Square");
Tooltip.install(rect, t);
This tooltip will then participate with the typical tooltip semantics (i.e. appearing
on hover, etc). Note that the Tooltip does not have to be uninstalled: it will be
garbage collected when it is not referenced by any Node. It is possible to manually
uninstall the tooltip, however.
A single tooltip can be installed on multiple target nodes or multiple controls.
Because most Tooltips are shown on UI controls, there is special API for all controls
to make installing a Tooltip less verbose. The example below shows how to create a
tooltip for a Button control:
import javafx.scene.control.Tooltip;
import javafx.scene.control.Button;

Button button = new Button("Hover Over Me");


button.setTooltip(new Tooltip("Tooltip for Button"));

FileChooser
public final class FileChooser
extends Object
Opens a file dialog to choose files or directories.
Provides support for standard platform file dialogs. These dialogs have look and feel
of the platform UI components which is independent of JavaFX.
On some platforms where file access may be restricted or not part of the user model
(for example, on some mobile or embedded devices), opening a file dialog may
always result in a no-op (that is, null file(s) being returned).
A FileChooser can be used to invoke file open dialogs for selecting single file
(showOpenDialog), file open dialogs for selecting multiple files
(showOpenMultipleDialog) and file save dialogs (showSaveDialog).
The configuration of the displayed dialog is controlled by the values of the
FileChooser properties set before the corresponding show Dialog method is called.
This configuration includes the dialog's title, the initial directory displayed in the
dialog and the extension filter(s) for the listed files. For configuration properties
which values haven't been set explicitly, the displayed dialog uses their platform
default values. A call to a show dialog method is blocked until the user makes a
choice or cancels the dialog. The return value specifies the selected file(s) or equals
to null if the dialog has been canceled.
Example:
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Text Files", "*.txt"),
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
new ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"),
new ExtensionFilter("All Files", "*.*"));
File selectedFile = fileChooser.showOpenDialog(mainStage);
if (selectedFile != null) {
mainStage.display(selectedFile);
}

You might also like