[Go to site: main page, start]

0% found this document useful (0 votes)
10 views33 pages

JavaFX GUI Programming Basics

This document provides an overview of Java GUI programming using JavaFX, including objectives for creating user interfaces, understanding stages, scenes, and nodes. It covers the structure of JavaFX applications, layout managers, and various UI controls, as well as the use of colors, fonts, and images. Additionally, it introduces the Model-View-Controller architecture for designing JavaFX applications.

Uploaded by

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

JavaFX GUI Programming Basics

This document provides an overview of Java GUI programming using JavaFX, including objectives for creating user interfaces, understanding stages, scenes, and nodes. It covers the structure of JavaFX applications, layout managers, and various UI controls, as well as the use of colors, fonts, and images. Additionally, it introduces the Model-View-Controller architecture for designing JavaFX applications.

Uploaded by

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

Chapter One

GUI Programming-
Java

1
Objectives
 To write a simple JavaFX program and understand the
relationship among stages, scenes, and nodes.
 To create user interfaces using panes, UI controls, and
shapes.
 To use the common properties style and rotate for
nodes.
 To create colors using the Color class.
 To create fonts using the Font class.
 To create images using the Image class and to create
image views using the ImageView class.
 To layout nodes using Pane, StackPane, FlowPane,
GridPane, BorderPane, HBox, and VBox .
 To display text using the Text class and create
2 shapes using Line, Circle, Rectangle, Ellipse, Arc,
Creating GUI Objects
// Create a button with text OK
Button btOK = new Button("OK");

// Create a label with text "Enter your name: "


Label lblName = new Label("Enter your name:"); Text Check Radio
field Box Butto
Label
n

Button

Combo
// Create a text field with text "Type Name Here"
TextField tfName = new TextField("Type Name Here");
Box

// Create a check box with text bold


CheckBox chkBold = new CheckBox("Bold");

// Create a radio button with text red


RadioButton rbRed = new RadioButton("Red");

// Create a combo box with choices red, green, and blue


ComboBox cboColor = new ComboBox(new String[]{"Red“,"Green“,"Blue"});
3
Graphical User Interface (GUI)
A graphical user interface (GUI)
presents a user-friendly mechanism for
interacting with an app.
GUIs are built from GUI components or
simply controls or widgets—short for
window gadgets.
A GUI component is an object with
which the user interacts via the mouse,
the keyboard or another form of input,
such as voice recognition.
There are three GUI Libraries in Java
4
 Abstract Windows Toolkit (AWT) API
Java GUI Programming
 When Java was introduced, the GUI classes were
bundled in a library known as the Abstract
Windows Toolkit (AWT).
 AWT was fine for developing simple graphical user
interfaces, but not for developing comprehensive GUI
projects.
 In addition, AWT is prone to platform-specific bugs.
 Later, the AWT user-interface components were
replaced by a more robust, versatile, and flexible
library known as Swing components.
 Swing components depend less on the target
platform and use less of the native GUI resources.
 For this reason, Swing components that don’t rely on
native GUI are referred to as lightweight components,
5 and AWT components are referred to as heavyweight
JavaFX Basic Concepts
 JavaFX is a newer framework for developing Java
GUI programs.
 JavaFX incorporates modern GUI technologies to
enable you to develop Rich Internet Applications.
 A rich Internet application (RIA) is a Web application
designed to deliver the same features and functions
normally associated with desktop applications.
 A JavaFX application can run seamlessly on a
desktop and from a Web browser.
 Additionally, JavaFX provides a multi-touch support
for touch-enabled devices such as tablets and smart
phones.
 JavaFX has a built-in 2D, 3D, animation support,

6
video and audio playback, and runs as a stand-alone
application or from a browser.
JavaFX Application Structure
JavaFX application is divided hierarchically into
three main components known as Stage, Scene
and Scene Graph or nodes.
1. Stage: Stage in a JavaFX application is similar to
the Frame in a Swing Application. It acts like a
container for all the JavaFX objects. Primary Stage
is created internally by the platform. The object of
primary stage is passed to start method. We need
to call show method on the primary stage
object in order to show our primary stage. It is
found in the package ([Link]) .
2. Scene: Scene actually holds all the physical
contents (nodes) of a JavaFX application.
[Link] class provides all the
7 methods to deal with a scene object. Creating
JavaFX Application Structure
The total object graph of all the controls, layouts
etc. attached to a scene is called the scene
graph.
Scene Graph can also be seen as the collection of
various nodes.
Node: A node is the element which is visualized on
the stage. It can be any button, text box, layout,
image, radio button, check box, etc.
A node is a visual component such as a shape, an
image view, a UI control, or a pane.
A shape refers to a text, line, circle, ellipse,
rectangle, arc, polygon, polyline, etc.
A UI control refers to a label, button, check box,
8 radio button, text field, text area, etc.

JavaFX Application Structure
There are two types of nodes: Branch nodes and
Leaf nodes.
A Branch node is a node that can contain other
nodes (child nodes).
Branch nodes are also referred to as parent nodes
because they can contain child nodes.
A Leaf node is a node which cannot contain other
nodes.

9
JavaFX Application Structure
The relationship among Stage, Scene, Node,
Control, and Pane is illustrated in the following
UML diagram.
Stage object is automatically
created by JVM when the
application is launched –
considered the window – you can
have multiple
Scene objectstages.
is the container
for the content – considered the
frame in the window – can have
only one scene per stage or
window
Button object (or node) is a
visual component such as a shape,
image, UI control, groups, and
panes. Used to invoke some type of
action
Container classes called panes can be used to help
layout the nodes within a scene. Control refers to a
label, check box, radio button, text field and etc.
10
JavaFX Application Structure
( 1 ) One Scene per Stage

( 2 ) A Scene can contain a


Control, Group or Pane

( 3 ) A Pane or Group can


contain any subtype of Node

11
JavaFX Layout Managers
 Layouts are the top level container classes that define
the UI styles for scene graph objects.
 Layout can be seen as the parent node to all the other
nodes.
 JavaFX provides various layout panes that support
different styles of layouts.
 All Layout classes belong to [Link]
package. [Link]
GridPane class is the
ScrollPan

base Pane
class for all the built-in
AnchorPalayout classese in JavaFX.
StackPan
SplitePan
ne
e e
TilePane
BorderPa
TextFlow Tab
ne TitledPan
HBox  Accordion
 e
12
VBox ButtonBa
ToolBar
JavaFX Layout Managers
 JavaFX provides many types of panes for
automatically laying out nodes in a desired location
and size.
Class Description
Base class for layout panes. It contains the getChildren()
Pane
method for returning a list of nodes in the pane.
Places the nodes on top of each other in the center of the
StackPane
pane.
FlowPane Places the nodes row-by-row horizontally .
GridPane Places the nodes in the cells in a two-dimensional grid.
Places the nodes in the top, right, bottom, left, and center
BorderPane
regions.
HBox Places the nodes in a single row.
VBox
Steps to create
Placeslayout: In in
the nodes order to create
a single the layouts, we need to
column.
follow the following steps.
 Instantiate the respective layout class, for example, HBox root = new
HBox();
13 Setting the properties for the layout, for example,
[Link](20);
JavaFX Layout Managers
FlowPane GridPane

BorderPane Hbox and VBox

14
The Color Class
• Each GUI component has background and foreground
colors.
• JavaFX defines the abstract Paint class for painting a
node.
• The [Link] is a concrete subclass
of Paint, which is used to encapsulate colors.
• A color constructor: public Color(double r, double g, double
b, double opacity); in which r, g, and b specify a color by
its red, green, and blue components with values in the
range from 0.0 (darkest shade) to 1.0 (lightest shade).
• The opacity value defines the transparency of a color
within the range from 0.0 (completely transparent) to
1.0 (completely opaque).
• This is known as the RGBA model, where RGBA stands
15for red, green, blue, and alpha. The alpha value
Standard Colors
• Alternatively, you can use one of the many
standard colors such as BEIGE, BLACK, BLUE,
BROWN, CYAN, DARKGRAY, GOLD, GRAY,
GREEN, LIGHTGRAY, MAGENTA, NAVY,
ORANGE, PINK, RED, SILVER, WHITE, and
YELLOW defined as constants in the Color
class.

Example:
Button btn = new Button("OK");
[Link]([Link]);
16
The Font Class
A Font describes font name, weight, and size.
You can set fonts for rendering the text.
The [Link] class is used to
create fonts.
A Font is defined by its name, weight,
posture, and size.
The font postures are two constants:
[Link] and
[Link].
Font font1 = new Font("SansSerif", 16);
Font font2 = [Link]("Times New Roman",
17 [Link], [Link], 12);
The Image and ImageView Classes
• The Image class represents a graphical image
and the ImageView class can be used to
display an image.
• The [Link] class is used
for loading an image from a specified filename
or a URL.
• The [Link] is a
node for displaying an image.
• An ImageView can be created from an Image
object.
• For example:
Image image = new Image("image/[Link]");
ImageView imageView = new ImageView(image);
•18 Alternatively, you can create an ImageView
JavaFX UI Controls
The package [Link] provides all the
necessary classes for the UI components .
Label  TextField  ContextMenu
Button  PasswordField  Separator

MenuButton  TextArea  TableView

SplitMenuBut  ImageView  TreeView


 DatePicker  TreeTableView
ton
ToggleButton  ColorPicker  HTMLEditor

RadioButton  Slider  Pagination


 Tooltip  FileChooser
CheckBox
 Hyperlink  DirectoryChoos
ChoiceBox
 ProgressBar er
ComboBox
 MenuBar  Accordion
19
ListView
Developing a Simple JavaFX
Application Program

In order to create a basic JavaFX application, we


need to:
 Import [Link] package
into our program.
 Our Program must be extended from Application
class.
 Override the start() method of the Application
class.

20
package javafxapplication;
import [Link]; Example of JavaFX GUI
import [Link]; Program
import [Link];
import [Link];
import [Link];
public class JavaFXApplication extends Application {
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
Button btn = new Button("Say 'Hello World'"); // Create a button
StackPane root = new StackPane(); // Create a layout
[Link]().add(btn); // Add a button on the layout
Scene scene = new Scene(root, 300, 250);// Create a scene and place a layout
in the scene
[Link]("Hello World!"); // Set the stage title
[Link](scene); // Place the scene in the stage
[Link](); // Display the stage
}
public static void main(String[] args) {
launch(args); //The JVM invokes launch method to run the application
}
}
21
JavaFX Application Class
The Application Class is the entry point for JavaFX
applications.
The class responsible for launching a JavaFX app
must be a subclass of Application class (package
[Link]).
We need to import
[Link] class in every
JavaFX application.
When the subclass’s main method is called:
1. Method main() calls class Application’s static
launch() method to
begin executing the app.
2. The launch method, in turn, causes the JavaFX
22 runtime to create an
object of the Application subclass and call its start
Cicle
One of Application's tasks is to manage the
application's life cycle.
The following overridable Application methods
play a role in this life cycle:
void init(): Initialize an application. An application
may override this method to perform initialization
before the application is
started. Application's init() method does nothing.
void start(Stage primaryStage): Start an
application. An application must override this
abstract method to provide the application's entry
point. The primaryStage argument specifies a
container for the user interface.
void stop(): Stop an application. An application
23
may override this method to prepare for application
JavaFX Application Life Cicle
The JavaFX runtime does the following, in order,
whenever an application is launched:
1. Create an instance of the class that
extends Application.
2. Invoke init() on the JavaFX Launcher Thread.
Because init() isn't invoked on the JavaFX
Application Thread, it must not
create [Link] or [Link] obj
ects, but may create other JavaFX objects.
3. Invoke start() on the JavaFX Application Thread
after init() returns and the JavaFX runtime is ready
for the JavaFX application to begin running.
4. Wait for the application to finish. The application
ends when it invokes [Link]() or when the
24 last window has been closed.
JavaFX Charts
JavaFX provides different types of classes for the
different types of charts.
All the chart classes of the package
[Link] are described in the
following table. Example of
AreaChart PieChart
BarChart
BubbleChart
LineChart
PieChart
ScatterChart
StackedAreaChart
StackedBarChart
25
JavaFX 2D and 3D Shapes
JavaFX contains features that make it
easy to draw 2D and 3D graphics on the
screen.
1. 2D shape classes 2. 3D shape
are classes are
Line Box
Rectangle Cylinder
Ellipse Sphere
Arc
Circle
Polygon
CubicCurve
QuadCurve
26
Model-View-Controller
Architecture
JavaFX enables you to design with Model-View-
Controller (MVC), through the use of FXML and
Java.
JavaFX applications in which the GUI is
implemented as FXML adhere to the Model-View-
Controller (MVC) design pattern.
MVC separates the JavaFX app’s data (contained
in the model) from the app’s GUI (the view) and
the app’s processing logic (the controller).
The controller implements logic for processing user
inputs.
The model contains application data, and the view
presents the data stored in the model.

27
When a user provides some input, the controller
Model-View-Controller
Architecture
We can create JavaFX GUI programs using two
ways:
JavaFX Application – using hard-coded (building the
GUI from scratch)
JavaFX FXML Application – using a Visual Design
tool (drag and drop)
The Scene Builder tool is a standalone JavaFX GUI
visual layout tool that can also be used with
various IDEs.
JavaFX Scene Builder enables you to create GUIs
by dragging and
dropping GUI components from Scene Builder’s
library onto a design
28area, then modifying and styling the GUI—all
Model-View-Controller
Architecture
As you create and modify a GUI, JavaFX Scene
Builder generates FXML (FX Markup Language)
—an XML vocabulary for defining and arranging
JavaFX GUI controls without writing any Java
code.
XML (eXtensible Markup Language) is a widely
used language for
describing things—it’s readable both by
computers and by humans.
FXML concisely describes GUI, graphics and
multimedia elements.
The FXML code is separate from the program
29logic that’s defined in Java source code.
Model-View-Controller
Architecture
When we create a JavaFX FXML Application
Project, the project opens three files
1. The FXML File: This file contains the FXML
markup language for the GUI.
2. The Main Class File: This is the main class
that creates the GUI from the FXML file and
displays the GUI in a window. This class
must be inherited from the Application class.
3. The Controller Class File: This class
typically defines instance variables for
interacting with controls programmatically
and event-handling methods that respond to
30 the user’s interactions. The controller class
The FXMLLoader Class
When a JavaFX FXML application begins
executing, class FXMLLoader’s static method
load() is used to load the FXML file that
represents the app’s GUI. This method:
 Creates the GUI’s scene graph—containing
the GUI’s layouts and controls—and returns a
Parent (package [Link]) reference to
the scene graph’s root node.
 Initializes the controller’s instance variables
for the components that are manipulated
programmatically.
 Creates and registers the event handlers for
31 any events specified in the FXML.
Other Features of JavaFX
 Web App
 WebView: The JavaFX WebView ([Link])
component is capable of showing web pages (HTML, CSS, SVG,
JavaScript) inside a JavaFX application.
 WebEngine: The JavaFX WebEngine
([Link]) is an internal component used
by the WebView to load the data that is to be displayed inside
the WebView.
 Cascading Style Sheet (CSS): JavaFX enables you to style
JavaFX components using CSS, just like you can style HTML
and SVG element in web pages with CSS.
 Audio: JavaFX contains features that makes it easy to
play audio in JavaFX applications. This is typically
useful in games or educational applications.
 Vedio: JavaFX contains features that makes it easy to
32 play video in JavaFX applications. This is typically
useful in streaming applications, games or
End!!
33

You might also like