Java Programming Chapter III

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

Wolaita Sodo University

School of Informatics
Department of Computer Science
Chapter Three
Java GUI using JAVAFX

Compiled by Dawit Uta. (M. Tech.)


Computer Science Department, WSU
website address: www.davidtechnotips.com
2 Course outline
Chapter 3: Java GUI using JAVAFX
3.1. JAVAFX architecture and Program structure
3.2. JAVAFX layout components
3.3. Basic UI controls
3.3.1. Event handlers
3.3.1. UI controls
3.4. Composite UI controls
3.5. Shapes
3.5.1. Color, Texts, Fonts
3.5.2. Lines, Circle, Rectangle
3.5.3. CSS styling
3.6. Properties and Bindings
3.7. Graphics and Animation
3
Introduction to GUI
 Many Java application use a graphical user interface or GUI (pronounced “gooey).

 A GUI is a graphical window or windows that provide interaction with the user.

 GUI’s accept input from:

– the keyboard

– a mouse.

 A window in a GUI consists of components that:

– present data to the user, allow interaction with the application.

 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

Same concepts as AWT


 Doesn’t work in ancient Java implementations (Java 1.1 and earlier)
 Many more controls, and they are more flexible
 Some controls, but not all, are a lot more complicated
 Gives a choice of “look and feel” packages
 Much easier to build an attractive GUI
Swing
9

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

Programmers cannot easily extend the AWT components.


AWT components are commonly called heavyweight components.
Swing was introduced with the release of Java 2.
Swing is a library of classes that provide an improved alternative for
creating GUI applications and applets.
Very few Swing classes rely on peer classes, so they are referred to
called lightweight components.
Swing draws most of its own components.
Swing components have a consistent look and predictable behavior on
any operating system.
Swing components can be easily extended.
12 AWT vs. Swing
Some of the AWT classes are used to determine when events, such as
the clicking of a mouse, take place in applications.
 In an application that uses an AWT class, it is necessary to use the
following import statement.
import java.awt.*;
Note that there is no x after java in this package name.
 In an application that uses Swing classes, it is necessary to use the
following import statement:
import javax.swing.*;
Note the letter x that appears after the word java.
13 AWT Vs. Swing
Swing is bigger, slower, and more complicated
 But not as slow as it used to be
 Swing is more flexible and better looking
 Swing and AWT are incompatible--you can use either, but you can’t
mix them
 Actually, you can, but it’s tricky and not worth doing
 Learning the AWT is a good start on learning Swing
 Many of the most common controls are just renamed
AWT: import java.awt.*;
AWT: Button b = new Button ("OK");
Swing: import javax.swing.*;
Swing: JButton b = new JButton("OK");
What is JavaFX?
14
 JavaFX is a Java library used to develop Desktop applications as well as Rich Internet
Applications (RIA).

 The applications built in JavaFX, can run on multiple platforms including Web, Mobile and
Desktops.

 JavaFX is intended to replace swing in Java applications as a GUI framework. However, It


provides more functionalities than swing.

 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

 Sun Micro-systems announces it officially in 2007 at W3 Conference. In October 2008,


JavaFX 1.0 was released.

 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

 Right-click on 'My Computer' and select 'Properties'.

 Click on the 'Environment Variables' button under the 'Advanced' tab.

 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");

//Creating the stop button


Button stopButton = new Button("stop");

Instantiating the Respective Class


After creating the nodes (and completing all the operations on them), instantiate the class of
the required layout.
For Example, if you want to create a Hbox layout, you need to instantiate this class as follows.
HBox hbox = new HBox();
Layouts
39

 Setting the Properties of the Layout


 After instantiating the class, you need to set the properties of the layout using their
respective setter methods.
 For example − If you want to set space between the created nodes in the HBox layout, then
you need to set value to the property named spacing. This can be done by using the setter
method setSpacing() as shown below
 hbox.setSpacing(10);
 Adding the Shape Object to the Group
 Finally, you need to add the object of the shape to the group by passing it as a parameter of
the constructor as shown below.
 Creating a Group object
Group root = new Group(line);
Layouts
40

S.No Shape & Description


1 Hbox The HBox layout arranges all the nodes in our application in a single horizontal row.
The class named HBox of the package javafx.scene.layout represents the text horizontal box layout.
2 Vbox The VBox layout arranges all the nodes in our application in a single vertical column.
The class named VBox of the package javafx.scene.layout represents the text Vertical box layout.
3 BorderPane The Border Pane layout arranges the nodes in our application in top, left, right, bottom and
center positions.
The class named BorderPane of the package javafx.scene.layout represents the border pane layout.
4 StackPane The stack pane layout arranges the nodes in our application on top of another just like in a
stack. The node added first is placed at the bottom of the stack and the next node is placed on top of it.
The class named StackPane of the package javafx.scene.layout represents the stack pane layout.
5 TextFlow The Text Flow layout arranges multiple text nodes in a single flow.
The class named TextFlow of the package javafx.scene.layout represents the text flow layout.
JavaFX Event handlers
41

 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

 If you click on the play button, the source will be the


mouse, the target node will be the play button and the
type of the event generated is the mouse click.
45
Event types are hierarchical. Every event type has a name and a super type. For example, the
name of the event for a key being pressed is KEY_PRESSED, and the super type
is KeyEvent.ANY. The super type of the top-level event type is null. Figure below shows a
subset of the hierarchy. Event Type Hierarchy
Event Handlers and Filters
46
 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, you can
provide a common filter/handler to the parents, which is processed as default for all the
child nodes.
 Adding and Removing Event Filter
 To add an event filter to a node, you need to register this filter using the
method addEventFilter() of the Node class.
public class EventHandlersExample2 extends Application {
Example 2 public void start(Stage stage) {
47 //Drawing a Box
package eventhandlersexample2; Box box = new Box();
import javafx.animation.RotateTransition; //Setting the properties of the Box
import javafx.application.Application; box.setWidth(150.0);
import javafx.event.EventHandler; box.setHeight(150.0);
import javafx.scene.Group; box.setDepth(100.0);
import javafx.scene.PerspectiveCamera; //Setting the position of the box
import javafx.scene.Scene; box.setTranslateX(350);
import javafx.scene.control.TextField; box.setTranslateY(150);
import javafx.scene.input.KeyEvent; box.setTranslateZ(50);
import javafx.scene.input.MouseEvent; //Setting the text
import javafx.scene.paint.Color; Text text = new Text("Type any letter to rotate the box,
import javafx.scene.paint.PhongMaterial; and click on the box to stop the rotation");
import javafx.scene.shape.Box; //Setting the font of the text
import javafx.scene.text.Font; text.setFont(Font.font(null, FontWeight.BOLD, 15));
import javafx.scene.text.FontWeight; //Setting the color of the text
import javafx.scene.text.Text; text.setFill(Color.CRIMSON);
import javafx.scene.transform.Rotate; //setting the position of the text
import javafx.stage.Stage; text.setX(20);
import javafx.util.Duration; text.setY(50);
Example 2 … //Creating a text filed
48 TextField textField = new TextField();
//Setting the material of the box //Setting the position of the text field
PhongMaterial material = new PhongMaterial(); textField.setLayoutX(50);
material.setDiffuseColor(Color.DARKSLATEBLUE); textField.setLayoutY(100);
//Setting the diffuse color material to box //Handling the key typed event
box.setMaterial(material); EventHandler<KeyEvent> eventHandlerTextField
//Setting the rotation animation to the box new EventHandler<KeyEvent>() {
RotateTransition rotateTransition = new @Override
RotateTransition(); public void handle(KeyEvent event) {
//Setting the duration for the transition //Playing the animation
rotateTransition.setDuration(Duration.millis(1000)); rotateTransition.play();
//Setting the node for the transition }
rotateTransition.setNode(box); };
//Setting the axis of the rotation //Adding an event handler to the text feld
rotateTransition.setAxis(Rotate.Y_AXIS); textField.addEventHandler(KeyEvent.KEY_TYPED,
//Setting the angle of the rotation eventHandlerTextField);
rotateTransition.setByAngle(360);
//Setting the cycle count for the transition //Handling the mouse clicked event(on box)
rotateTransition.setCycleCount(50); EventHandler<MouseEvent> eventHandlerBox =
//Setting auto reverse value to false new EventHandler<MouseEvent>() {
rotateTransition.setAutoReverse(false);
Source code
49
@Override PerspectiveCamera(false);
public void handle(MouseEvent e) { camera.setTranslateX(0);
rotateTransition.stop(); camera.setTranslateY(0);
} camera.setTranslateZ(0);
}; scene.setCamera(camera);
//Adding the event handler to the box //Setting title to the Stage
box.addEventHandler(MouseEvent.MOUSE_CLI stage.setTitle("Event Handlers Example");
CKED, eventHandlerBox); //Adding scene to the stage
//Creating a Group object stage.setScene(scene);
Group root = new Group(box, textField, //Displaying the contents of the stage
text); stage.show();
//Creating a scene object }
Scene scene = new Scene(root, 600, 300); public static void main(String args[]){
//Setting camera launch(args);
PerspectiveCamera camera = new }
}
Output of the program
50

You might also like