0% found this document useful (0 votes)
4 views

GUI Using JavaFX Components

The document provides an overview of Java GUI programming using JavaFX, detailing its objectives, components, and structure, including stages, scenes, and nodes. It covers the creation of user interfaces, layout managers, and various UI controls, as well as the JavaFX application lifecycle. Additionally, it discusses the Color and Font classes, and introduces the Image and ImageView classes for handling graphics in JavaFX applications.

Uploaded by

mulukenh724
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)
4 views

GUI Using JavaFX Components

The document provides an overview of Java GUI programming using JavaFX, detailing its objectives, components, and structure, including stages, scenes, and nodes. It covers the creation of user interfaces, layout managers, and various UI controls, as well as the JavaFX application lifecycle. Additionally, it discusses the Color and Font classes, and introduces the Image and ImageView classes for handling graphics in JavaFX applications.

Uploaded by

mulukenh724
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
You are on page 1/ 33

Chapter One

GUI Programming-
Java
Faculty Of Computing,
Bahir Dar Institute of Technology,
Bahir Dar University
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
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"});
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
 Abstract Windows Toolkit (AWT) API
 Swing API since java version 1.2
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, and AWT
components are referred to as heavyweight components.
 Swing is designed for developing desktop GUI applications.
 With the release of Java 8, Swing is replaced by a completely
new GUI platform known as JavaFX.
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, video and
audio playback, and runs as a stand-alone application or from a
browser.
 JavaFX is the new GUI tool for developing cross-platform-rich
Internet applications on desktop computers, on hand-held
devices, and on the Web.
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
(javafx.stage.Stage) .
2. Scene: Scene actually holds all the physical contents (nodes)
of a JavaFX application. Javafx.scene.Scene class provides
all the methods to deal with a scene object. Creating scene is
necessary in order to visualize the contents on the stage.
3. Scene Graph: All visual components (controls, layouts etc.)
must be attached to a scene to be displayed, and that scene
must be attached to a stage for the whole scene to be visible.
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, radio button,
text field, text area, etc.
 All components attached to the scene graph are called nodes.
 All nodes are subclasses of a JavaFX class called
javafx.scene.Node
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.
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
Scenemultiple
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.
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
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 javafx.scene.layout package.
javafx.scene.layout.Pane class is the base class for all the
built-in layout classes in JavaFX.

 GridPane  ScrollPane
 Pane
 AnchorPane  SplitePane
 StackPane
 TilePane  Tab
 BorderPane
 TextFlow  TitledPane
 HBox
 Accordion  ToolBar
 VBox
 ButtonBar
 FlowPane
 DialogPane
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 Places the nodes in a single column.
 Steps to create layout: In order to create the layouts, we need to follow the
following steps.
 Instantiate the respective layout class, for example, HBox root = new HBox();
 Setting the properties for the layout, for example, root.setSpacing(20);
 Adding nodes to the layout object, for example,
root.getChildren().addAll(<NodeObjects>);
JavaFX Layout Managers
FlowPane GridPane

BorderPane Hbox and VBox


The Color Class
• Each GUI component has background and foreground colors.
• JavaFX defines the abstract Paint class for painting a node.
• The javafx.scene.paint.Color 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 for red,
green, blue, and alpha. The alpha value indicates the opacity.
• For example,
Color color = new Color(0.25, 0.14, 0.333, 0.51);
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");
btn.setTextFill(Color.RED);
The Font Class
A Font describes font name, weight, and size.
You can set fonts for rendering the text.
The javafx.scene.text.Font class is used to
create fonts.
A Font is defined by its name, weight,
posture, and size.
The font postures are two constants:
FontPosture.ITALIC and
FontPosture.REGULAR.
Font font1 = new Font("SansSerif", 16);
Font font2 = Font.font("Times New Roman",
FontWeight.BOLD, FontPosture.ITALIC, 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 javafx.scene.image.Image class is used for
loading an image from a specified filename or a URL.
• The javafx.scene.image.ImageView is a node for
displaying an image.
• An ImageView can be created from an Image object.
• For example:
Image image = new Image("image/us.gif");
ImageView imageView = new ImageView(image);
• Alternatively, you can create an ImageView directly
from a file or a URL as follows:
ImageView imageView = new ImageView("image/us.gif");
JavaFX UI Controls
The package javafx.scene.control 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
ListView
Developing a Simple JavaFX
Application Program

In order to create a basic JavaFX application, we


need to:
 Import javafx.application.Application package
into our program.
 Our Program must be extended from Application
class.
 Override the start() method of the Application
class.
package javafxapplication;
import javafx.application.Application; Example of JavaFX GUI
import javafx.scene.Scene; Program
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
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
root.getChildren().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
primaryStage.setTitle("Hello World!"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public static void main(String[] args) {
launch(args); //The JVM invokes launch method to run the application
}
}
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
javafx.application).
 We need to import javafx.application.Application
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 runtime to
create an
object of the Application subclass and call its start method.
3. The Application subclass’s start method creates the GUI,
attaches
it to a Scene and places it on the Stage that start method
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 may override
this method to prepare for application exit and to destroy
resources. Application's stop() method does nothing.
JavaFX Application Life Cicle
 TheJavaFX 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 javafx.scene.Scene or javafx.stage.Stage objects, 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 Platform.exit() or when the last window has been
closed.
5. Invoke stop() on the JavaFX Application Thread. After this
method returns, the application exits.
JavaFX Charts
JavaFX provides different types of classes for the
different types of charts.
All the chart classes of the package
javafx.scene.chart are described in the
following table. Example of
AreaChart PieChart
BarChart
BubbleChart
LineChart
PieChart
ScatterChart
StackedAreaChart
StackedBarChart
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
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.
 When a user provides some input, the controller
modifies the model with the given input.
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
area, then modifying and styling the GUI—all without writing any
code.
 JavaFX Scene Builder’s live editing and preview features allow you
to
view your GUI as you create and modify it, without compiling and
running the app.
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 logic that’s defined in
Java source code.
 Separation of the interface (the GUI) from the implementation (the
Java code) makes it easier to debug, modify and maintain JavaFX
GUI apps.
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 the user’s interactions.
The controller class may also declare additional
instance variables, static variables and methods
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 javafx.scene) 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
any events specified in the FXML.
Other Features of JavaFX
 Web App
 WebView: The JavaFX WebView (javafx.scene.web.WebView)
component is capable of showing web pages (HTML, CSS, SVG,
JavaScript) inside a JavaFX application.
 WebEngine: The JavaFX WebEngine (javafx.scene.web.WebEngine)
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 play
video in JavaFX applications. This is typically useful in streaming
applications, games or educational applications.
 Animation: It enables the movement or motion of objects.
End!!

You might also like