Java Programming Chapter III
Java Programming Chapter III
Java Programming Chapter III
School of Informatics
Department of Computer Science
Chapter Three
Java GUI using JAVAFX
A GUI is a graphical window or windows that provide interaction with the user.
– the keyboard
– a mouse.
The JavaFX is a set of Java libraries designed to enable developers to create and deploy rich
client applications that behave consistently across platforms.
Introduction to GUI ….
4 GUI components
.
5
Introduction to GUI ….
Java programmers use the Java Foundation Classes (JFC) to create GUI
applications.
The JFC consists of several sets of classes
The two sets of JFC classes that we focus on are AWT and Swing classes.
Java is equipped with a set of classes for drawing graphics and creating
graphical user interfaces.
These classes are part of the Abstract Windowing Toolkit (AWT).
The AWT allows creation of applications and applets with GUI
components.
The AWT does not actually draw user interface components on the screen.
6 AWT
Some common AWT GUI components are:
– buttons, labels, text fields, check boxes, radio buttons, combo boxes,
and sliders.
7
AWT
The AWT communicates with a layer of software, peer classes.
Each version of Java for a particular operating system has its own set of peer classes.
The AWT is roughly broken into three categories
Components
Layout Managers
Graphics
Many AWT components have been replaced by Swing components
Java programs using the AWT:
look consistent with other applications on the same system.
can offer only components that are common to all the operating systems that support
Java.
The behavior of components across various operating systems can differ.
8 Swing
Containers
Contain and manage other components
Top Level/Internal
Examples: JFrame (Top Level), JScrollPane, Jpanel
Basic Controls
Atomic components
Used for showing output and/or getting some input
Inherits Jcomponent
Examples: JButton, JLabel, JTextArea, JTable, Jlist
Usually every Swing class extends the corresponding AWT class
For backward-compatibility reasons
Swing Components
10
AWT vs. Swing
11
The applications built in JavaFX, can run on multiple platforms including Web, Mobile and
Desktops.
Like Swing, JavaFX also provides its own components and doesn't depend upon the
operating system. It is lightweight and hardware accelerated.
It supports various operating systems including Windows, Linux and Mac OS.
JAVAFX architecture and Program structure
15
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
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.
JAVAFX architecture and Program structure
16
Figure 1
Scene Graph
The JavaFX scene graph, shown as part of the top layer in Figure 1, is the starting point for
constructing a JavaFX application. It is a hierarchical tree of nodes that represents all of the
visual elements of the application's user interface. It can handle input and can be rendered.
JAVAFX architecture and Program structure
17
To develop GUI Applications using Java programming language, the programmers rely on
libraries such as Advanced Windowing Tool kit and Swing. After the advent of JavaFX,
these Java programmers can now develop GUI applications effectively with rich content.
The applications developed using JavaFX can run on various devices such as Desktop
Computers, Mobile Phones, TVs, Tablets, etc..
History of JavaFX
JavaFX was developed by Chris Oliver. Initially the project was named as Form Follows
Functions (F3) .
It is intended to provide the richer functionalities for the GUI application development.
Later, Sun Micro-systems acquired F3 project as JavaFX in June, 2005
JAVAFX architecture and Program structure
18
In 2009, ORACLE corporation acquires Sun Micro-Systems and released JavaFX 1.2. the
latest version of JavaFX is JavaFX 1.8 which was released on 18th March 2014.
Features of JavaFX
Feature Description
Java Library It is a Java library which consists of many classes and interfaces that are written
in Java.
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.
Features of JavaFX
19
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 JavaFX contains Built-in components which are not dependent on operating
controls system. The UI component are just enough to develop a full featured
application.
CSS like 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 The JavaFX applications can be embedded with swing code using the Swing
interoperability Node class. We can update the existing swing application with the powerful
features of JavaFX.
Features of JavaFX
20
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 An integrated set of classes are provided to deal with 2D and 3D graphics.
Library
Graphics Pipeline JavaFX graphics are based on Graphics rendered pipeline(prism). It offers
smooth graphics which are hardware accelerated.
High Performance The media pipeline supports the playback of web multimedia on a low
Media Engine latency. It is based on a Gstreamer Multimedia framework.
Self-contained Self Contained application packages have all of the application resources
application and a private copy of Java and JavaFX Runtime.
deployment model
JavaFX UI Controls
21
Every graphical user interface of every desktop application mainly considers three main aspects UI
elements, layouts and behavior.
UI elements:- These are the core visual elements which the user eventually sees and interacts with.
JavaFX provides a huge list of widely used and common elements varying from basic to complex.
Layouts:- They define how UI elements should be organized on the screen and provide a final look
and feel to the GUI.
Behavior:- These are events which occur when the user interacts with UI elements.
JavaFX provides several classes in the package javafx.scene.control. To create various GUI
components (controls), JavaFX supports several controls such as label, button, text field, etc.
Each control is represented by a class; you can create a control by instantiating its respective class.
JavaFX UI Controls cont…
22
Following are the lists of commonly used controls while the GUI is designed using JavaFX
SN Control Description
1 Label Label is a component that is used to define a simple text on the screen.
Typically, a label is placed with the node, it describes.
2 Button Button is a component that controls the function of the application. Button
class is used to create a labelled button.
3 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.
4 CheckBox Check Box is used to get the kind of information from the user which
contains various choices. User marked the checkbox either on (true) or
off(false).
5 Menu JavaFX provides a Menu class to implement menus. Menu is the main
component of any application.
JavaFX UI Controls cont…
23
6 TextField Text Field is basically used to get the input from the user in the form of text.
javafx.scene.control.TextField represents TextField
7 PasswordField PasswordField is used to get the user's password. Whatever is typed in the
passwordfield is not shown on the screen to anyone.
8 HyperLink HyperLink are used to refer any of the webpage through your appication. It
is represented by the class javafx.scene.control.HyperLink
9 Slider Slider is used to provide a pane of options 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.
10 ProgressBar Progress Bar is used to show the work progress to the user. It is represented
by the class javafx.scene.control.ProgressBar.
11 ScrollBar JavaFX Scroll Bar is used to provide a scroll bar to the user so that the user
can scroll down the application pages.
JavaFX – Environment setup
24
From Java8 onwards, the JDK (Java Development Kit) includes JavaFX library in it.
Therefore, to run JavaFX applications, you simply need to install Java8 or later version in
your system.
Visit the JavaSE Downloads Page, click on the JDK Download button and install it.
In addition to it, IDE’s like Eclipse and NetBeans provide support for JavaFX.
NetBeans provides inbuilt support for JavaFX. On installing this, you can create a JavaFX
application without any additional plugins or JAR files.
Visit the NetBeans website and click the Download button in order to download the
NetBeans software and install it.
Setting up the Path for Windows
25
After installing Java, you need to set the path variables. Assume that you have installed
Java in C:\Program Files\java\jdk1.8.0_91directory.
Now you can follow the steps that are given below
Now, alter the 'Path' variable so that it also contains the path to the Java executable. For
Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path
to read 'C:\WINDOWS\SYSTEM32; C:\Program Files\java\ jdk1.8.0_91\bin'.
Setting up the Path for Windows …
26
JavaFX Application Structure
27 In general, a JavaFX application will have three major components namely Stage,
Scene and Nodes as shown in the following diagram.
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.
You have to call the show() method to display the contents
of a stage.
Scene represents the physical contents of a JavaFX
application. It contains all the contents of a scene graph.
Creating a JavaFX Application
28
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.
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 as shown in the following
program. 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); }
}
Creating JavaFx application using Netbeans IDE
29
After installing Netbeans and JDK tool, open Netbeans then click the file menu, select New
Project… to open the New project wizard as shown in the following screenshot.
Creating JavaFx application using Netbeans IDE
30 …New Project wizard, select JavaFX and click on Next. It starts creating a
In the
new JavaFX Application for you.
Creating JavaFx application using Netbeans IDE
31 …the name of the project and location of the project in the NewJavaFX
Select
Application window and then click Finish. It creates a sample application with
the given name.
Creating JavaFx application using Netbeans IDE
32 …instance, an application with a name javafxsample is created. Within this application, the
In this
NetBeans IDE will generate a Java program with the name Javafxsample.java. As shown in the following
screenshot, this program will be created inside NetBeans Source Packages → javafxsample.
Creating JavaFx application using Netbeans IDE
33 …
Right-click on the file and select Run File to run this code as shown in the
following screenshot.
Creating JavaFx application using Netbeans IDE
34 …automatically created program contains the code which generates a simple
This
JavaFX window having a button with the label Say ‘Hello World’ in it. Every time you click
on this button, the string Hello World will be displayed on the console as shown below..
Source code
35
package javafxapplication1;
import javafx.application.Application;
import javafx.event.ActionEvent; });
import javafx.event.EventHandler; StackPane root = new StackPane();
import javafx.scene.Scene; root.getChildren().add(btn);
import javafx.scene.control.Button; Scene scene = new Scene(root, 300, 250);
import javafx.scene.layout.StackPane; primaryStage.setTitle("Hello World!");
import javafx.stage.Stage; primaryStage.setScene(scene);
public class javafxsample extends Application { primaryStage.show();
@Override }
public void start(Stage primaryStage) { /**
Button btn = new Button(); * @param args the command line arguments
btn.setText("Say 'Hello World '"); */
btn.setOnAction(new EventHandler<ActionEvent>() public static void main(String[] args) {
{@Override launch(args);
public void handle(ActionEvent event) { }
System.out.println("Hello World!"); }
}
Layouts
36
After constructing all the required nodes in a scene, we will generally arrange them in
order.
This arrangement of the components within the container is called the Layout of the
container. We can also say that we followed a layout as it includes placing all the
components at a particular position within the container.
JavaFX provides several predefined layouts such as HBox, VBox, Border Pane, Stack
Pane, Text Flow, Anchor Pane, Title Pane, Grid Pane, Flow Panel, etc.
Each of the above mentioned layout is represented by a class and all these classes belongs
to the package javafx.layout.
The class named Pane is the base class of all the layouts in JavaFX.
Layouts
37
Creating a Layout
To create a layout, we need to
• Create node
• Instantiate the respective class of the required layout.
• Set the properties of the layout.
• Add all the created nodes to the layout.
Creating Nodes
First of all, create the required nodes of the JavaFX application by instantiating their
respective classes.
For example, if we want to have a text field and two buttons namely, play and stop in a
HBox layout, we will have to initially create those nodes as shown in the following code
block
Layouts
38
//Creating a text field //Creating the play button
TextField textField = new TextField(); Button playButton = new Button("Play");
In JavaFX applications, events are notifications that something has happened. For example,
clicking on a button, pressing a keys, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes an
event to happen. Event Handling is the mechanism that controls the event and decides what
should happen, if an event occurs.
Registered event filters and event handlers within the application receive the event and
provide a response.
Types of Events: The events can be broadly classified into the following two categories
Foreground Events: events which require the direct interaction of a user. They are generated
as consequences of a person interacting with the graphical components in a GUI.
JavaFX Event handlers
42
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: 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.
JavaFX provides support to handle a wide varieties of events. The class named Event of
the package javafx.event is the base class for an event.
JavaFX Event handlers
43
JavaFX provides a wide variety of events. Some of them are listed below.
Mouse Event − This is an input event that occurs when a mouse is clicked. It is represented
by the class named MouseEvent. It includes actions like mouse clicked, mouse pressed,
mouse released, mouse moved, mouse entered target, mouse exited target, etc.
Key Event − This is an input event that indicates the key stroke occurred on a node. It is
represented by the class named KeyEvent. This event includes actions like key pressed,
key released and key typed.
Drag Event − This is an input event which occurs when the mouse is dragged. It is
represented by the class named DragEvent. It includes actions like drag entered, drag
dropped, drag entered target, drag exited target, drag over, etc.
Window Event − This is an event related to window showing/hiding actions. It is
represented by the class named WindowEvent. It includes actions like window hiding,
window shown, window hidden, window showing, etc.
44
JavaFX provides handlers and filters to handle events. In JavaFX every event has −
Target: The node on which an event occurred. A target can be a window, scene, and a node.
Source: The source from which the event is generated will be the source of the event. In the
above scenario, mouse is the source of the event.
Type: Type of the occurred event; in case of mouse event – mouse pressed, mouse released
are the type of events.
Assume that we have an application which has a Circle, Stop and Play Buttons inserted
using a group object as follows