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

Chapter 02

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapter 02

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Java Programming (COSC -3053)

Chapter 02
Java GUI using JAVAFX

1
Objectives
After studying this chapter, students should be able to:
 Learn about Graphical User Interface (GUI)
 provides user-friendly human interaction

 Understand Building Java GUIs require use of frameworks:


 AWT
 Swing
 JavaFX (part of Java since JSE 8, 2014) includes:
 GUI components
 Event Programming
 Graphics

2
Graphical User Interface (GUI)
What is a “GUI“ in java?
● It refers to an interface that allows user to interact with electronic devices like
computers and tablets through graphic elements.
● It uses icons, menus and other graphical representations to display information, as
opposed to text-based commands.
● It gives an application a distinctive “look” and “feel.”.

● provides user-friendly human interaction

● GUIs are built from GUI components. These are sometimes called controls or
widgets.
● It plays an important role to build easy interfaces for Java applications.

● 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.

3
Cont.
 How do GUIs work?
They loop and respond to events
Example: a mouse click on a button
• Operating System recognizes mouse click
• determines which window it was inside
• notifies that program
• Program runs in loop
• checks input buffer filled by OS
• if it finds a mouse click:
• determines which component in the program
• if the click was on a relevant component
• respond appropriately according to handler

4
Cont.
 GUI Look vs. Behavior
• Look • Behavior
• physical appearance • Interactivity
• custom component design • event programmed response
• Containment
• layout management
 Java GUI APIs: Java has three GUI packages

Provides ready made visible, interactive, customizable components

you wouldn’t want to have to code your own window
 The original Abstract Windows Toolkit (AWT) and
 The Swing.
 The newer JavaFX

5
JavaFX vs Swing and AWT
 Swing and AWT are replaced by the JavaFX platform for developing rich Internet
applications in JDK8 (2014)
 History:

When Java was introduced (1996), the GUI classes were bundled in a library known as the
Abstract Windows Toolkit (AWT)

AWT was prone to platform-specific bugs

AWT was fine for developing simple graphical user interfaces, but NOT for developing
comprehensive GUI projects

The AWT user-interface components were replaced by a more robust, versatile, and flexible
library known as Swing components (1997)

Swing components are painted directly on canvases using Java code

Swing components depend less on the target platform and use less of the native GUI resource
 With the release of Java 8, Swing is replaced by a completely new GUI platform:
JavaFX

6
JAVAFX architecture and Program structure
 JavaFX is a Java library used to build Rich Internet Applications. The applications
written using this library can run consistently across multiple platforms.
 The applications developed using JavaFX can run on various devices such as Desktop
Computers, Mobile Phones, TVs, Tablets, etc..
 Rich Internet Applications are those web applications which provide similar features
and experience as that of desktop applications
 They offer a better visual experience when compared to the normal web applications
to the users
 These applications are delivered as browser plug-ins or as a virtual machine and are
used to transform traditional static applications into more enhanced, fluid,
animated and engaging applications.
 JavaFX provides a complete API with a rich set of classes and interfaces to build
GUI applications with rich graphics. The important packages of this API are −

7
Cont..
 javafx.animation − Contains classes to add transition based animations such as fill,
fade, rotate, scale and translation, to the JavaFX nodes.
 javafx.application − Contains a set of classes responsible for the JavaFX application
life cycle.
 javafx.css − Contains classes to add CSS–like styling to JavaFX GUI applications.
 javafx.event − Contains classes and interfaces to deliver and handle JavaFX events.
 javafx.geometry − Contains classes to define 2D objects and perform operations on
them.
 javafx.stage − This package holds the top level container classes for JavaFX
application.
 javafx.scene − This package provides classes and interfaces to support the scene
graph.
 In addition, it also provides sub-packages such as canvas, chart, control, effect,
image, input, layout, media, paint, shape, text, transform, web, etc.
 There are several components that support this rich API of JavaFX.

8
Cont..
 JavaFX architecture
javaFX API Scene Graph

Quantum Toolkit

javaFX Graphic Engine


Prism Glass Web view Media

Win32/GTK Open GL/D3D Web kit G streams

JDK API and Tools

Java Virtual Machine


9
Cont..
Scene Graph

In JavaFX, the GUI Applications were coded using a Scene Graph.

A Scene Graph is the starting point of the construction of the GUI Application. It holds the (GUI)
application primitives that are termed as nodes.
 A node is a visual/graphical object and it may include

Geometrical (Graphical) objects − (2D and 3D) such as circle, rectangle, polygon, etc.

UI controls − such as Button, Checkbox, Choice box, Text Area, etc.

Containers − (layout panes) such as Border Pane, Grid Pane, Flow Pane, etc.

Media elements − such as audio, video and image objects.
 A collection of nodes makes a scene graph. All these nodes are arranged in a
hierarchical order as shown below.

10
Cont..
Prism

Prism is a high performance hardware–accelerated graphical pipeline that is used to render the
graphics in JavaFX. It can render both 2-D and 3-D graphics.
 To render graphics, a Prism uses −

DirectX 9 on Windows XP and Vista.

DirectX 11 on Windows 7.

OpenGL on Mac and Linux, Embedded Systems.
GWT (Glass Windowing Toolkit)

As the name suggests, GWT provides services to manage Windows, Timers, Surfaces and Event
Queues.

GWT connects the JavaFX Platform to the Native Operating System.
Quantum Toolkit

It is an abstraction over the low-level components of Prism, Glass, Media Engine, and Web Engine.

It ties Prism and GWT together and makes them available to JavaFX.
WebView

Using JavaFX, you can also embed HTML content in to a scene graph.

WebView is the component of JavaFX which is used to process this content. It uses a technology
called Web Kit
11
Cont..
Media Engine

The JavaFX media engine is based on an open-source engine known as a Streamer.

This media engine supports the playback of video and audio content.

The JavaFX media engine provides support for audio for the following file formats −

 The package javafx.scene.media contains the classes and interfaces to provide media
functionality in JavaFX.
 It is provided in the form of three components, which are −

Media Object − This represents a media file

Media Player − To play media content.

Media View − To display media.

12
JavaFX Application Structure
 JavaFX application will have three major components namely Stage, Scene and Nodes

Stage
• A stage (a window) contains all the objects of a JavaFX
application.
• It is represented by Stage class of the
package javafx.stage. the primary stage is created by the
platform itself.
• The created stage object is passed as an argument to
the start() method of the Application class
• A stage has two parameters determining its position
namely Width and Height.
• It is divided as Content Area and Decorations (Title Bar
and Borders).

13
Cont..
 There are five types of stages available −

Decorated

Undecorated

Transparent

Unified

Utility
 You have to call the show() method to display the contents of a stage.
Scene

A scene represents the physical contents of a JavaFX application. It contains all the contents of a
scene graph.

The class Scene of the package javafx.scene represents the scene object. At an instance, the scene
object is added to only one stage.

You can create a scene by instantiating the Scene Class.

You can option for the size of the scene by passing its dimensions (height and width) along with
the root node to its constructor.

14
Cont..
Scene Graph and Nodes
 A scene graph is a tree-like data structure (hierarchical) representing the contents of a

scene.
 In contrast, a node is a visual/graphical object of a scene graph.
 A node may include −

Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.

UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.

Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.

Media elements such as Audio, Video and Image Objects.
 The Node Class of the package javafx.scene represents a node in JavaFX, this class is
the super class of all the nodes.
 Root Node − The first Scene Graph is known as the Root node.
 Branch Node/Parent Node − The node with child nodes are known as branch/parent
nodes.
 The abstract class named Parent of the package javafx.scene is the base class of all
the parent nodes, and those parent nodes will be of the following types

15
Cont..

Group − A group node is a collective node that contains a list of children nodes.

Whenever the group node is rendered, all its child nodes are rendered in order.

Any transformation, effect state applied on the group will be applied to all the child nodes.

Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and
Control.

WebView − This node manages the web engine and displays its contents.
Leaf Node

The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box,
ImageView, MediaView are examples of leaf nodes.
 Its mandatory to pass the root node to the scene graph.
 If the Group is passed as root, all the nodes will be clipped to the scene and any
alteration in the size of the scene will not affect the layout of the scene.

16
Creating a JavaFX Application
 To create a JavaFX application, you need to instantiate the Application class and implement its
abstract method start().
 In this method, we will write the code for the JavaFX Application.

Application Class
 The Application class of the package javafx.application is the entry point of the application in

JavaFX.
 To create a JavaFX application, you need to inherit this class and implement its abstract method start().
 In this method, you need to write the entire code for the JavaFX graphics
 In the main method, you have to launch the application using the launch() method.
 This method internally calls the start() method of the Application class

public class JavafxSample extends Application


{
@Override public void start(Stage primaryStage) throws
Exception {
/* Code for JavaFX application. (Stage, scene, scene
graph) */
}
public static void main(String args[]){ launch(args);
}
}
17
Cont..
 Within the start() method:-you need to follow the steps given below ,

Prepare a scene graph with the required nodes.

Prepare a Scene with the required dimensions and add the scene graph (root node of the scene
graph) to it.

Prepare a stage => add the scene to the stage => display the contents of the stage.
Preparing the Scene Graph

Since the root node is the first node, you need to create a root node.

As a root node, you can choose from the Group, Region or WebView.
 Group − A Group node is represented by the class named Group which belongs to the

package javafx.scene,
Group root = new
 The getChildren() method Group();
of the Group class gives you an object of the ObservableList class which
holds the nodes

//Retrieving the observable list object


ObservableList list = root.getChildren();
//Setting the text object as a node
list.add(NodeObject);
18
Cont.
 add Node objects to the group, just by passing them to the Group class and to its
constructor at the time of instantiation,
Group root = new Group(NodeObject);
Region − It is the Base class of all the JavaFX Node-based UI Controls,

Chart − This class is the base class of all the charts and it belongs to the package
javafx.scene.chart.

This class has two sub classes, which are − PieChart and XYChart. These two in turn have
subclasses such as AreaChart, BarChart, BubbleChart

You can use these classes to embed charts in your application.

Pane − A Pane is the base class of all the layout panes such as
AnchorPane, BorderPane, DialogPane, etc

This class belong to a package that is called as − javafx.scene.layout.

You can use these classes to insert predefined layouts in your application.

Control − It is the base class of the User Interface controls such as

Accordion, ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc.

This class belongs to the package javafx.scene.control.

19
Cont..
 //Creating a Stack Pane
StackPane pane = new StackPane();
//Adding text area to the pane
ObservableList list = pane.getChildren();
list.add(NodeObject);
 WebView: This node manages the web engine and displays its contents.

20
Cont..
Creating Scene
 A JavaFX scene is represented by the Scene class of the package javafx.scene.
 create a Scene by instantiating this class as shown in the following cod block
 While instantiating, it is mandatory to pass the root object to the constructor of the

scene class. Height


Scene scene = new Scene(root); Width

Scene scene = new Scene(root, 600, Group object


300);
Creating Stage
 Stage is the container of any JavaFX application and it provides a window for the

application.
 It is represented by the Stage class of the package javafx.stage.
 An object of this class is passed as a parameter of the start() method of

the Application class.

21
Cont..
operations on the stage

Set the title for the stage using the method setTitle().

Attach the scene object to the stage using the setScene() method.

Display the contents of the scene using the show() method
Lifecycle of JavaFX Application

start() − The entry point method where the JavaFX graphics code is to be written.

stop() − An empty method which can be overridden, here you can write the logic to stop the
application.

init() − An empty method which can be overridden, but you cannot create stage or scene in this
method.
Terminating the JavaFX Application

When the last window of the application is closed, the JavaFX application is terminated implicitly.

turn this behavior off by passing the Boolean value “False” to the static method
setImplicitExit() (should be called from a static context).

You can terminate a JavaFX application explicitly using
themethods Platform.exit() or System.exit(int).

22
Cont..
 Example: program generates an empty JavaFX window
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavafxSample extends Application {
@Override public void start(Stage primaryStage) throws Exception {
//creating a Group object
Group group = new Group();
//Creating a Scene by passing the group object, height and width
Scene scene = new Scene(group ,600, 300);
//setting color to the scene
scene.setFill(Color.BROWN);
//Setting the title to Stage.
primaryStage.setTitle("Sample Application");
//Adding the scene to Stage
primaryStage.setScene(scene);
//Displaying the contents of the stage
primaryStage.show();
}
public static void main(String args[]){ launch(args);
}
}

23
Cont..
 Example: program shows to generate a straight line using JavaFX
import
javafx.application.Application;
//Creating a Group
import javafx.scene.Group;
Group root = new Group(line);
import javafx.scene.Scene; //Creating a Scene
import javafx.scene.shape.Line; Scene scene = new Scene(root, 600, 300
import javafx.stage.Stage;
public class DrawingLine extends //Setting title to the scene
Application{ stage.setTitle("Sample application");
@Override //Adding the scene to the stage
public void start(Stage stage) { stage.setScene(scene);
//Creating a line object //Displaying the contents of a scene
stage.show();
Line line = new Line();
}
//Setting the properties to a line public static void main(String args[]
line.setStartX(100.0); { launch(args);
line.setStartY(150.0); }
line.setEndX(500.0); }
line.setEndY(150.0);
24
Cont.. @Override public void start(Stage stage)
{
//Creating a Text object
Text text = new Text();
//Setting font to the text
text.setFont(new Font(45));
//setting the position of the text
text.setX(50); text.setY(150);
//Setting the text to be added.
text.setText("Welcome to java");
//Creating a Group object
Group root = new Group();
//Retrieving the observable list object
ObservableList list =
root.getChildren();
//Setting the text object as a node to
Example: Following is the program to display text using the group object
list.add(text);
JavaFX //Creating a scene object
import javafx.application.Application; Scene scene = new Scene(root, 600,
import javafx.collections.ObservableList; 300);
import javafx.scene.Group; //Setting title to the Stage
import javafx.scene.Scene; stage.setTitle("Sample Application");
import javafx.stage.Stage; //Adding scene to the stage
import javafx.scene.text.Font; stage.setScene(scene);
//Displaying the contents of the stage
import javafx.scene.text.Text; stage.show();
public class DisplayingText extends Application { }
public static void main(String args[]){
launch(args); 25
Cont..

26
Basic UI controls
 javaFX provides an extensive set of classes that can be used to add a GUI to our
applications. A GUI control performs at least one of these functions

Displays Information

Collects data from the user

Allows the user to initiate program functions

27
Cont..
 Hierarchy of some javaFX control, recall that because of the “is a “ relationship in inheritance, a
subclass object is also an object of each of its super classes.
 All controls are Node (element of the scene), a parent (a Node that can have children controls ).
 Along hierarchies each controls gained methods and properties for its super classes.

28
Cont..
 In application controls are placed into scene by using layout containers,
 which organize the controls according to each layout’s rules

29
Cont..
 Layout classes also inherit from Node, parent and region, instead of inheriting from
control.
 Layout defines the way in which the components are to be seen on the stage
 Inherit from Pane which provides a method for accessing all the children in the scene
graph

30
Cont..
 Steps to create layout

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>);
BorderPane

arranges the nodes at the left, right, centre, top and bottom of the screen.

It is represented by javafx.scene.layout.BorderPane class.

This class provides various methods like setRight(), setLeft(), setCenter(),
setBottom() and setTop() which are used to set the position for the specified nodes.

instantiate BorderPane class to create the BorderPane layout.
 BorderPane() : create the empty layout
 BorderPane(Node Center) : create the layout with the center node
 BorderPane(Node Center, Node top, Node right, Node bottom, Node left) : create
the layout with all the nodes
BorderPane BPane = new BorderPane();

31
Cont..
JavaFX HBox

HBox layout pane arranges the nodes in a single row. It is represented by
javafx.scene.layout.HBox class.

instantiate HBox class in order to create HBox layout.
setAlignment(double),setFillHeight(double),
setSpacing(double)
 HBox class contains two constructors.

new HBox() : create HBox layout with 0 spacing

new Hbox(Double spacing) : create HBox layout with a spacing value
HBox root = new HBox();
JavaFX VBox

arranges the nodes in a single vertical column.

It is represented by javafx.scene.layout.VBox class which provides all the methods to deal with the
styling and the distance among the nodes.

instantiated in order to implement VBox layout in our application.
setAlignment(double),setFillwidth(double),
setSpacing(double)
32
Cont..
 Constructors
VBox() : creates layout with 0 spacing
Vbox(Double spacing) : creates layout with a spacing value of double type
Vbox(Double spacing, Node? children) : creates a layout with the specified spacing
among the specified child nodes
Vbox(Node? children) : creates a layout with the specified nodes having 0 spacing among
them
VBox root = new VBox();
JavaFX StackPane

StackPane layout pane places all the nodes into a single stack where every new node gets placed
on the top of the previous node.

It is represented by javafx.scene.layout.StackPane class.

instantiate this class to implement StackPane layout into our application.
setAlignment(Nodechild,pos value),setAlignment(pos value)
 The class contains two constructors

StackPane()

StackPane(Node? Children)
StackPane root = new StackPane();
33
Cont..
JavaFX GridPane

GridPane Layout pane allows us to add the multiple nodes in multiple rows and columns.

It is seen as a flexible grid of rows and columns where nodes can be placed in any cell of the grid.

It is represented by javafx.scence.layout.GridPane class.

instantiate this class to implement GridPane.
setAlignment(pos value), setGridLinesVisible(boolean value),
setHgap(double vlue),setVgap(double value)
 Constructors

Public GridPane(): creates a gridpane with 0 hgap/vgap.
GridPane root=new GridPane();
JavaFX FlowPane

FlowPane layout pane organizes the nodes in a flow that are wrapped at the flowpane's boundary.

The horizontal flowpane arranges the nodes in a row and wrap them according to the flowpane's
width.

The vertical flowpane arranges the nodes in a column and wrap them according to the flowpane's
height.

FlowPane layout is represented by javafx.scene.layout.FlowPane class.

instantiate this class to create the flowpane layout.
34
Cont..
setAlignment(pos value), setColumnHalignment(Hpos value), setHgap(double
value),setOrientation(Orientation value),setpredWraplength(double value),
setRowValignment (vpos value),setVgap(double value).
 Constructors

FlowPane()

FlowPane(Double Hgap, Double Vgap)

FlowPane(Double Hgap, Double Vgap, Node? children)

FlowPane(Node... Children)

FlowPane(Orientation orientation)

FlowPane(Orientation orientation, double Hgap, Double Vgap)

FlowPane(Orientation orientation, double Hgap, Double Vgap, Node?
children )

FlowPane(Orientation orientation, Node... Children)

FlowPane root = new FlowPane();

35
JavaFX Label
 javafx.scene.control.Label class represents label control.
 The label is the component that is used to place any text information on the screen.
 It is mainly used to describe the purpose of the other components to the user.
 You can not set a focus on the label using the Tab key.
 Package: javafx.scene.control

Constructors:

Label(): creates an empty Label

Label(String text): creates Label with the supplied text

Label(String text, Node graphics): creates Label with the supplied text and graphic
s

36
Cont..

package application; StackPane root = new StackPane();
import javafx.application.Application; Scene scene=new Scene(root,300,300);
import javafx.scene.Scene; root.getChildren().add(my_label);
import javafx.scene.control.Label; primaryStage.setScene(scene);
import javafx.scene.layout.StackPane; primaryStage.setTitle("Label Class Exa
import javafx.stage.Stage; mple");
public class LabelTest extends Applicati primaryStage.show();
on { }
@Override public static void main(String[] arg
public void start(Stage primaryStage) th s) {
rows Exception { launch(args);
// TODO Auto- }
generated method stub }
Label my_label=new Label("This is
an example of Label");

37
JavaFX Button
 JavaFX button control is represented by javafx.scene.control.Button class.
 A button is a component that can control the behaviour of the Application.
 An event is generated whenever the button gets clicked.
 How to create a Button?
 Button can be created by instantiating Button class. Button btn = new Button("My Button");
StackPane root = new StackPane();
package application; Button btn=new Button("This is a
import javafx.application.Application; button");
import javafx.scene.Scene; Scene scene=new Scene(root,300,3
import javafx.scene.control.Button; 00);
import javafx.scene.layout.StackPane; root.getChildren().add(btn);
import javafx.stage.Stage; primaryStage.setScene(scene);
public class ButtonTest extends Application primaryStage.setTitle("Button Cl
{ ass Example");
primaryStage.show();
@Override
public void start(Stage primaryStage) t }
hrows Exception { public static void main(String[] arg
// TODO Auto- s) {
generated method stub launch(args);
} } 38
Cont..
RadioButton
• The Radio Button is used to provide various options to the user.
• The user can only choose one option among all.
• A radio button is either selected or deselected.
• It can be used in a scenario of multiple choice questions in the quiz where
package application; only one option needs to be chosen
import javafx.application.Application;
import javafx.scene.Scene; RadioButton button3 = new RadioButton("option 3");
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup; RadioButton button4 = new RadioButton("option 4");
import javafx.scene.layout.VBox;
import javafx.stage.Stage; button1.setToggleGroup(group);
public class RadioButtonTest extends Application { button2.setToggleGroup(group);
button3.setToggleGroup(group);
public static void main(String[] args) { button4.setToggleGroup(group);
launch(args); VBox root=new VBox();
} root.setSpacing(10);
@Override root.getChildren().addAll(button1,button2,button3,b
public void start(Stage primaryStage) throws Exception utton4);
{ Scene scene=new Scene(root,400,300);
// TODO Auto-generated method stub primaryStage.setScene(scene);
ToggleGroup group = new ToggleGroup(); primaryStage.setTitle("Radio Button Example");
RadioButton button1 = new RadioButton("option 1"); primaryStage.show(); 39
Cont.

JavaFX CheckBox
• The Check Box is used to provide more than one choices to the user.
• It can be used in a scenario where the user is prompted to select more than one option or the user
wants to select multiple options.
• It is different from the radio button in the sense that, we can select more than one checkboxes in a
scenerio.
• Instantiate javafx.scene.control.CheckBox class to implement CheckBox.
CheckBox checkbox = new CheckBox();
CheckBox checkbox = new CheckBox("Label Name");
• change the CheckBox Label at any time by calling an instance method setText("text").
• selected by calling setSelected("true")
40
Cont.
HBox root = new HBox();
package application; root.getChildren().addAll(l,c1,c2,c3,c4);
import javafx.application.Application; root.setSpacing(5);
import javafx.scene.Scene; Scene scene=new Scene(root,800,200);
import javafx.scene.control.CheckBox; primaryStage.setScene(scene);
import javafx.scene.control.Label; primaryStage.setTitle("CheckBox Example");
import javafx.scene.layout.HBox; primaryStage.show();
import javafx.stage.Stage; }
public class CheckBoxTest extends Application { }

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage primaryStage) throws Ex
ception {
// TODO Auto-generated method stub
Label l = new Label("What do you listen:
");
CheckBox c1 = new CheckBox("Radio one");
CheckBox c2 = new CheckBox("Radio Mirchi");

CheckBox c3 = new CheckBox("Red FM");


CheckBox c4 = new CheckBox("FM GOLD"); 41
JavaFX TextField
 Text Field is basically used to get the input from the user in the form of text.
 javafx.scene.control.TextField represents TextField.
 It provides various methods to deal with textfields in JavaFX.
 TextField can be created by instantiating TextField class.
Lets see an example where the user is shown the two text boxes and prompted to
fill its user-id and password.
package application;
import javafx.application.Application; TextField tf1=new TextField();
import javafx.scene.Scene; TextField tf2=new TextField();
import javafx.scene.control.Button; Button b = new Button("Submit");
import javafx.scene.control.Label; GridPane root = new GridPane();
import javafx.scene.control.TextField; root.addRow(0, user_id, tf1);
import javafx.scene.layout.GridPane; root.addRow(1, password, tf2);
import javafx.stage.Stage; root.addRow(2, b);
public class TextFieldTest extends Application { Scene scene=new Scene(root,800,200);
public static void main(String[] args) { primaryStage.setScene(scene);
launch(args); primaryStage.setTitle("Text Field Example")
} primaryStage.show();
@Override }
public void start(Stage primaryStage) throws Exception }
{
// TODO Auto-generated method stub
Label user_id=new Label("User ID");
Label password = new Label("Password"); 42
Cont..
• TextField class provides an instance method getText() to retrieve the
textfield data.
• It returns String object which can be used to save the user details in
database.

JavaFX PasswordField
• However, typing a password in a text field is not secure for the user.
• The Application must use a specific component to get the password from the user.
• Passwordfield can be created by instantiating javafx.scene.control.PasswordField class.
• PasswordField class contains a method named as setPromptText() for showing a prompt text to the user in
password field.
• The data written in the passwordfield is retrieved by getText() method.

Example:

43
Cont.
package application;
GridPane root = new GridPane();
import javafx.application.Application;
import javafx.scene.Scene; root.addRow(0, user_id, tf);
import javafx.scene.control.Button; root.addRow(1, password, pf);
import javafx.scene.control.Label;
root.addRow(5, b);
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField; Scene scene=new Scene(root,300,200);
import javafx.scene.layout.GridPane; primaryStage.setScene(scene);
import javafx.stage.Stage;
primaryStage.setTitle("PasswordField Exampl
public class PasswordFieldTest extends Applicatio
n { e");
primaryStage.show();
public static void main(String[] args) { }
launch(args); }
}

@Override
public void start(Stage primaryStage) throws Exce
ption {
// TODO Auto-generated method stub
Label user_id=new Label("User ID");
Label password = new Label("Password");
TextField tf=new TextField();
PasswordField pf=new PasswordField();
pf.setPromptText("Enter Password");
Button b = new Button("Submit");
44
JavaFX HyperLink
 In JavaFx, w use hyper-links to refer the web pages. It is similar to anchor links in HTML.
 javafx.scene.control.HyperLink class provides all the necessary methods to deal with JavaFX hyper-
links.
package application; -> System.out.println("Link Clicked"));
import javafx.application.Application; root.getChildren().add(hp);
import javafx.scene.Scene; Scene scene=new Scene(root,400,300);
import javafx.scene.control.Hyperlink; primaryStage.setScene(scene);
import javafx.scene.layout.StackPane; primaryStage.setTitle("Hyperlink Example");
import javafx.stage.Stage; primaryStage.show();
public class HyperLinkTest extends Application { }
}

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception
{
// TODO Auto-generated method stub

Hyperlink hp = new Hyperlink("http://www.javatpoint.com


");
StackPane root = new StackPane();
hp.setOnAction(e
45
JavaFX Slide
 JavaFX slider is used to provide a pane of option to the user in a graphical form
 where the user needs to move a slider over the range of values to select one of them.
 Slider can be created by instantiating javafx.scene.control.Slider class.
 The constructor accepts three arguments: the minimum value, the maximum value,
and the initial value of the slider.
Scene scene = new Scene(root,300,200);
package application; primaryStage.setScene(scene);
import javafx.application.Application; primaryStage.setTitle("Slider Example
import javafx.scene.Scene; ");
import javafx.scene.control.Slider; primaryStage.show();
import javafx.scene.layout.StackPane;
import javafx.stage.Stage; }
public class SliderTest extends Application{ public static void main(String[] args) {

@Override launch(args);
public void start(Stage primaryStage) throws Except } }
ion {
// TODO Auto-generated method stub
Slider slider = new Slider(1,100,20);
StackPane root = new StackPane();
root.getChildren().add(slider);

46
JavaFX ProgressBar
 Progress Bar is used to show the work progress to the user.
 It is represented by javafx.scene.control.ProgressBar.
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ProgressBarTest extends Application {
public void start(Stage primaryStage) throws Excepti
on {
// TODO Auto-generated method stub
StackPane root = new StackPane();
ProgressBar progress = new ProgressBar();
root.getChildren().add(progress);
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("Progress Bar Example");
primaryStage.show();

}
public static void main(String[] args) {
launch(args);
}
} 47
JavaFX Progress Indicator
 Progress Indicator is similar to Progress Bar to some extent. Instead of showing the analogue progress
to the user, it shows the digital progress so that the user may know the amount of work done in
percentage.
 It is represented by javafx.scene.control.ProgressIndicator class.
 This class needs to be instantiated in order to create Progress Indicator.
package application;
import javafx.application.Application;
import javafx.scene.Scene; primaryStage.setScene(scene);
import javafx.scene.control.ProgressIndicator; primaryStage.setTitle("Progress
import javafx.scene.layout.StackPane; Indicator Example");
import javafx.stage.Stage; primaryStage.show();
public class Progress_Indicator extends Application{
}
@Override public static void main(String[] arg
public void start(Stage primaryStage) throws Except s) {
ion { launch(args);
// TODO Auto-generated method stub }
ProgressIndicator PI=new ProgressIndicator();
}
StackPane root = new StackPane();
root.getChildren().add(PI);
Scene scene = new Scene(root,300,200);

48
Cont..
Using setProgress() Method
Add the following lines to the code shown above in order to set the 75 %
progress value.

ProgressIndicator PI=new ProgressIndicator(


);
PI.setProgress(0.75f);

49
JavaFX ScrollBar
 JavaFX Scroll Bar is used to provide a scroll bar to the user so that the user can scroll
down the application pages.
 instantiating javafx.scene.control.ScrollBar class.
package application; primaryStage.setTitle("ScrollBar Example");
import javafx.application.Application; primaryStage.show();
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar; }
import javafx.scene.layout.StackPane; public static void main(String[] args) {
import javafx.stage.Stage;
public class ScrollBar extends Application{ launch(args);
}
@Override
public void start(Stage primaryStage) throws Except }
ion {
// TODO Auto-generated method stub
ScrollBar s = new ScrollBar();
StackPane root = new StackPane();
root.getChildren().add(s);
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);

50
Cont.
Setting values and orientation

As we see in the modern days application, the scrollbar is shown horizontally as well as vertically.
In JavaFX, we can set any of the orientation for the scrollbar. setOrientation() and passing
the Orientation.VERTICAL property into the method as an argument.

ScrollBar class also provide three methods named as:

setMin()

setMax()

setValue()

these methods are used to set the minimum, maximum and current value of the scrollbar. It decides
span of the scrollbar. package application;
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Progress_Indicator extends Application{

@Override
publicvoid start(Stage primaryStage) throws Excepti
on {
// TODO Auto-generated method stub
51
Cont..
ScrollBar s = new ScrollBar();
s.setMin(0);
s.setMax(200);
s.setValue(110);
s.setOrientation(Orientation.VERTICAL);
s.setUnitIncrement(12);
s.setBlockIncrement(10);
StackPane root = new StackPane();
root.getChildren().add(s);
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("ScrollBar Example");
primaryStage.show();

}
public static void main(String[] args) {
launch(args);
}

52
JavaFX FileChooser
 JavaFX File chooser enables users to browse the files from the file system.
 javafx.stage.FileChooser class represents FileChooser. It can be created by instantiating FileChooser
class.
 It contains two main methods.
 There are two types of dialogues shown to the user, one is for opening the file and the other is for
saving the files.
 In each case, the user needs to browse a location for the file and give the name to the file.

The FileChooser class provides two types of methods,

showOpenDialog()
public void start(Stage primaryStage) throws Exception

showSaveDialog() {
// TODO Auto-generated method stub
package application; FileChooser file = new FileChooser();
import javafx.application.Application; file.setTitle("Open File");
import javafx.scene.Scene; file.showOpenDialog(primaryStage);
import javafx.scene.control.Button; HBox root = new HBox();
import javafx.scene.control.Label; root.setSpacing(20);
import javafx.scene.control.TextField; Scene scene = new Scene(root,350,100);
import javafx.scene.layout.HBox; primaryStage.setScene(scene);
import javafx.stage.FileChooser; primaryStage.setTitle("FileChooser Example");
import javafx.stage.Stage; primaryStage.show();
public class FileChooserExample extends Application{
}
@Override public static void main(String[] args) {
53
launch(args);
Cont..
Example 2:
The following code shows a Label, TextField and a Button to the
user. An open file dialogue box will open on clicking the browse
button.
Label label = new Label("File:");
TextField tf= new TextField();
Button btn = new Button("Browse");
btn.setOnAction(e->
{
FileChooser file = new FileChooser();
package application; file.setTitle("Open File");
import javafx.application.Application; file.showOpenDialog(primaryStage);
import javafx.scene.Scene; });
import javafx.scene.control.Button; HBox root = new HBox();
import javafx.scene.control.Label; //root.getChildren().add(file);
import javafx.scene.control.TextField; root.setSpacing(20);
import javafx.scene.layout.HBox; root.getChildren().addAll(label,tf,btn);
import javafx.stage.FileChooser; Scene scene = new Scene(root,350,100);
import javafx.stage.Stage; primaryStage.setScene(scene);
public class FileChooserExample extends Application{ primaryStage.setTitle("FileChooser Example");
primaryStage.show();
@Override
public void start(Stage primaryStage) throws Except }
ion { public static void main(String[] args) {
// TODO Auto-generated method stub launch(args); 54
Cont..

JavaFX Menu
• JavaFX provides a Menu class to implement menus.
• Menu is the main component of a any application.
• In JavaFX, javafx.scene.control.Menu class provides all the methods to
deal with menus.
• This class needs to be instantiated to create a Menu.

• ManuBar menubar = new MenuBar(); //creating MenuBar


• Menu MenuName = new Menu("Menu Name"); //creating Menu
• MenuItem MenuItem1 = new MenuItem("Menu Item 1 Name"); //
creating Menu Item
• MenuName.getItems().add(MenuItem1); //adding Menu Item to the Menu
• menubar.getMenus().add(MenuName); //adding Menu to the MenuBar

55
Cont.
package application;
import javafx.application.Application; root.setTop(menubar);
import javafx.scene.Scene; FileMenu.getItems().addAll(filemenu1,filemenu2,
import javafx.scene.control.*; filemenu3);
import javafx.scene.layout.BorderPane; menubar.getMenus().addAll(FileMenu,EditMenu);
import javafx.stage.Stage; primaryStage.setScene(scene);
public class MenuExample extends Application { primaryStage.show();
public static void main(String[] args) {
launch(args); }
} }

@Override
public void start(Stage primaryStage) throws
Exception {
// TODO Auto-generated method stub
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");

EditMenu.getItems().addAll(EditMenu1,EditM 56
JavaFX Tooltip
 JavaFX Tool tip is used to provide hint to the user about any component.
 It is mainly used to provide hints about the text fields or password fields being used
in the application.
 It can be created by instantiating javafx.scene.control.Tooltip class.
package application; primaryStage.setTitle("ToolTip Example");
import javafx.application.Application; primaryStage.show();
import javafx.scene.Scene;
import javafx.scene.control.PasswordField; }
import javafx.scene.control.Tooltip; public static void main(String[] args) {
import javafx.scene.layout.StackPane; launch(args);
import javafx.stage.Stage; }
public class ProgressBarTest extends Application { }
public void start(Stage primaryStage) throws
Exception {
// TODO Auto-generated method stub
PasswordField pf = new PasswordField();
Tooltip tool=new Tooltip();
StackPane root = new StackPane();
tool.setText("Information");
pf.setTooltip(tool);
root.getChildren().add(pf);

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


primaryStage.setScene(scene); 57
Event handlers
 An event represents an occurrence of something of interest to the application, such as

Mouse being moved or key being pressed
 In javaFX, an event is an instance of the javafx.event.Event class or any subclass of
Event
 Every javaFX event has

eventType:-Type of the occurred event; in case of mouse event – mouse pressed, mouse released
are the type of events.

Source:- source from which the event is generated will be the source of the event.

Target:-node on which an event occurred. A target can be a window, scene, and a node.
 JavaFX provides several events, including DragEvent, KeyEvent,MouseEvent, ScrollEvent,
and other.
 You can define your own event by extending the event class
 Subclasses can define type specific properties

MouseEvent:x:y

KeyEvent:code,character

DragEvent

WindowEvent

58
Types of Events
Foreground Events −
 Those events which require the direct interaction of a user.
 They are generated as consequences of a person interacting with the graphical

components in a Graphical User Interface.


 For example, clicking on a button, moving the mouse, entering a character through keyboard,

selecting an item from list, scrolling the page, etc.


Background Events −
 Those events that don't require the interaction of end-user are known as

background events.
 The operating system interruptions, hardware or software failure, timer expiry,

operation completion are the example of background events.

59
Cont.

60
Types of Events hierarchy

61
Phases of Event Handling in JavaFX
 Whenever an event is generated, JavaFX undergoes the following phases.
Route Construction

Whenever an event is generated, the default/initial route of the event is determined by construction
of an Event Dispatch chain.

It is the path from the stage to the source Node.

62
Cont..
Event Capturing Phase
 After the construction of the event dispatch chain, the root node of the application

dispatches the event.


 This event travels to all nodes in the dispatch chain (from top to bottom).
 If any of these nodes has a filter registered for the generated event, it will be

executed.
 If none of the nodes in the dispatch chain has a filter for the event generated, then it

is passed to the target node and finally the target node processes the event.
Event Bubbling Phase
 In the event bubbling phase, the event is travelled from the target node to the stage

node (bottom to top).


 If any of the nodes in the event dispatch chain has a handler registered for the
generated event, it will be executed.
 If none of these nodes have handlers to handle the event, then the event reaches the

root node and finally the process will be completed.

63
Cont..
Event Handlers and Filters
 Event filters and handlers are those which contains application logic to process an

event.
 A node can register to more than one handler/filter.
 In case of parent–child nodes, provide a common filter/handler to the parents, which

is processed as default for all the child nodes.


 during the event, processing is a filter that is executed and during the event bubbling

phase, a handler is executed.


 All the handlers and filters implement the interface EventHandler of the

package javafx.event.

64
example
import javafx.application.Application;
import javafx.event.EventHandler; circle.setStrokeWidth(20);
import javafx.scene.Group; //Setting the text
import javafx.scene.Scene; Text text = new Text("Click on the circle to change its
import javafx.scene.input.MouseEvent; color");
import javafx.scene.paint.Color; //Setting the font of the text
import javafx.scene.shape.Circle; text.setFont(Font.font(null, FontWeight.BOLD, 15));
import javafx.scene.text.Font; //Setting the color of the text
import javafx.scene.text.FontWeight; text.setFill(Color.CRIMSON);
import javafx.scene.text.Text; //setting the position of the text
import javafx.stage.Stage; text.setX(150); text.setY(50);
public class EventFiltersExample extends //Creating the mouse event handler
Application { EventHandler<MouseEvent> eventHandler = new
@Override EventHandler<MouseEvent>() {
public void start(Stage stage) @Override public void handle(MouseEvent e)
{ //Drawing a Circle { System.out.println("Hello World");
Circle circle = new Circle(); circle.setFill(Color.DARKSLATEBLUE); } };
//Setting the position of the circle //Registering the event filter
circle.setCenterX(300.0f); circle.addEventFilter(MouseEvent.MOUSE_CLICKED,
circle.setCenterY(135.0f); eventHandler);
//Setting the radius of the circle //Creating a Group object
circle.setRadius(25.0f); Group root = new Group(circle, text);
//Setting the color of the circle //Creating a scene object
circle.setFill(Color.BROWN);
//Setting the stroke width of the circle

65
Cont..
Scene scene = new Scene(root, 600, 300);
//Setting the fill color to the scene
scene.setFill(Color.LAVENDER);
//Setting title to the Stage
stage.setTitle("Event Filters Example");
//Adding scene to the stage
stage.setScene(scene); /
/Displaying the contents of the stage
stage.show(); }
public static void main(String args[]){ launch(args);
} }

When red circle is clicked

66
Example
import javafx.application.Application; StackPane root = new StackPane();
import javafx.event.ActionEvent; root.getChildren().add(btn);
import javafx.event.EventHandler;
import javafx.scene.Scene; Scene scene = new Scene(root, 300, 250);
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane; primaryStage.setTitle("Button Example");
import javafx.stage.Stage; primaryStage.setScene(scene);
primaryStage.show();
public class ButtonExample extends Application }
{
public static void main(String[] args) {
@Override launch(args);
public void start(Stage primaryStage) { }
Button btn = new Button(); }
btn.setText("Say 'Hello World'");
btn.setOnAction(new
EventHandler<ActionEvent>() {

@Override
public void handle(ActionEvent
event) {
System.out.println("Hello
Click
World!");
}
});

67
Example1
import javafx.application.Application; // Register the event handler with the button
import javafx.event.ActionEvent; button.setOnAction(eventHandler);
import javafx.event.EventHandler;
import javafx.scene.Scene; StackPane root = new StackPane();
import javafx.scene.control.Button; root.getChildren().add(button);
import javafx.scene.layout.StackPane;
import javafx.stage.Stage; Scene scene = new Scene(root, 300, 200);

public class EventHandlerExample extends Application { primaryStage.setTitle("Event Handler Example");


primaryStage.setScene(scene);
public static void main(String[] args) { primaryStage.show();
launch(args); }
} }

@Override
public void start(Stage primaryStage) {
Button button = new Button("Click me!");

// Create an event handler for the button


EventHandler<ActionEvent> eventHandler = new
EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Button clicked!");
}
};
68
Example2
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler; newRoot.getChildren().add(backButton);
import javafx.scene.Scene; Scene newScene = new Scene(newRoot,
import javafx.scene.control.Button; 300, 200);
import javafx.scene.layout.StackPane;
import javafx.stage.Stage; // Create an event handler for the back
button
public class EventHandlingWithSceneExample extends EventHandler<ActionEvent>
Application { backEventHandler = new EventHandler<ActionEvent>() {
@Override
public static void main(String[] args) { public void handle(ActionEvent
launch(args); event) {
} // Go back to the original
scene
@Override primaryStage.setScene(scene);
public void start(Stage primaryStage) { }
Button button = new Button("Click me!"); };

// Create an event handler for the button // Register the event handler with the
back button
EventHandler<ActionEvent> eventHandler = new
EventHandler<ActionEvent>() {
@Override backButton.setOnAction(backEventHandler);
public void handle(ActionEvent event) {
// Create a new scene // Set the new scene on the primary
stage
StackPane newRoot = new StackPane();
Button backButton = new Button("Go primaryStage.setScene(newScene);
} 69
Back");
Cont.
// Register the event handler with the button
button.setOnAction(eventHandler);

StackPane root = new StackPane();


root.getChildren().add(button);

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

primaryStage.setTitle("Event Handling with


Scene Example");
primaryStage.setScene(scene);
primaryStage.show();
}
}

70

You might also like