Chapter 01 GUI-v2
Chapter 01 GUI-v2
INSTITUTE OF TECHNOLOGY
SCHOOL OF COMPUTING
DEPARTMENT OF SOFTWARE
ENGINEERING
ADVANCED PROGRAMMING
CHATER 1 GUI
LECTURE BY DEMEKE G.
1
Introduction
Definition of User Interface
✓ The user provides the input by typing a command string with the
✓ The use of pictures rather than just words to represent the input
5
Cont..
✓ In java, to develop an application that has a graphical user
6
Cont..
✓ Swing is an improved version of the AWT
✓ Some AWT classes are replaced by Swing classes, but other AWT
7
a FX
Jav
8
Introduction
✓ JavaFX is next-generation java GUI package
9
cont..
✓ JavaFX platform provides a rich set of graphics and
media API with high performance hardware-
accelerated graphics and media engines that simplify
the development of data-driven enterprise client
applications.
✓ JavaFX applications will run on any desktop and
browser that runs the JRE and easily integrate with Java
Platform, Mobile Edition (Java ME), opening the door
to billions of mobile phones and other connected
devices.
10
cont..
✓ JavaFX also leverages the other benefits of the Java
platform, such as object-orientation, inheritance,
polymorphism, a well-established security model, well-
defined exception handling, memory management through
garbage collection, and the mature Java Virtual Machine
(JVM).
✓ The reason why developers select javafx is JavaFX
platform contains an essential set of tools and technologies
that enable developers and designers to collaborate, create,
and deploy applications with expressive content.
11
Basic Structure of JavaFX
▪ javafx.application.Application class defines the essential framework for writing
JavaFX programs
▪ Every JavaFX program is defined in a class that extends javafx.application.Application
Stage object is automatically created by
Stage JVM when the application is launched –
considered the window – you can have
Scene multiple stages.
Output of program displays a The launch method is static method used for
launching stand-alone JavaFX apps. Not
button in the window needed if you run it from a command line.
14
JavaFX Program with Multiple Stages
Every JavaFX program extends
javafx.application.Application
15
1. Stage Class
✓ A stage in JavaFX is a top-level container that hosts a scene, which
consists of visual elements.
✓ The Stage class in the javafx.stage package represents a stage in a
JavaFX application.
✓ The stage has four variables that either affect its appearance or
reflect its active state.
✓ When a JavaFX application is launched, a stage known as the
primary stage is automatically created.
✓ A reference to this stage is passed to the application’s start method
via the primaryStage parameter:
16
Showing the primary stage
import javafx.application.Application;
import javafx.stage.Stage;
public class First_stage extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage stage) {
// Do write any code here
}
}
17
Setting the Bounds of a Stage
✓ The bounds of a stage consist of four properties: x, y,
width, and height.
✓ The x and y properties determine the location (or
position) of the upper-left corner of the stage.
@Override
public void start(Stage stage) {
Group root = new Group(new Button("Hello"));
Scene scene = new Scene(root);
stage.setScene(scene);
Rectangle2D bounds = Screen.getPrimary().getVisualBounds();
double x = bounds.getMinX() + (bounds.getWidth() - stage.getWidth())/2.0;
double y = bounds.getMinY() + (bounds.getHeight() - stage.getHeight())/2.0;
stage.setX(x);
stage.setY(y); stage.show();
}
18
Contt..
✓ The width and height properties determine its size.
@Override
public void start(Stage stage) {
stage.setTitle("A Sized Stage with a Sized Scene");
Group root = new Group(new Button("Hello"));
Scene scene = new Scene(root, 300, 100);
stage.setScene(scene);
stage.setWidth(400);
stage.setHeight(100);
stage.show();
}
19
Initializing the Style of a Stage
✓ The area of a stage can be divided into two parts:
content area and decorations.
✓ The content area displays the visual content of its scene.
✓ Typically, decorations consist of a title bar and borders.
✓ The presence of a title bar and its content varies
depending on the type of decorations provided by the
platform.
✓ Title bar may consists of title word, minimize,
maximize, restore, and close button.
20
Cont..
✓ the style attribute of a stage determines its background color
and decorations. Based on styles, you can have the following
five types of stages in JavaFX:
✓ Decorated stage has a solid white background and platform
decorations.
✓ An undecorated stage has a solid white background and no
decorations.
✓ A transparent stage has a transparent background and no
decorations.
✓ A unified stage has platform decorations and no border
between the client area and decorations; the client area
background is unified with the decorations.
21
Cont..
✓ To see the effect of the unified stage style, the scene should
be filled with Color.TRANSPARENT. Unified style is a
conditional feature.
✓ A utility stage has a solid white background and minimal
platform decorations.
• StageStyle.DECORATED StageStyle.UNIFIED
• StageStyle.UNDECORATED StageStyle.UTILITY
• StageStyle.TRANSPARENT
stage.initStyle(StageStyle. UTILITY)
22
Initializing Modality of a Stage
✓ In a GUI application, you can have two types of windows: modal
and modeless.
✓ In modal window the user cannot work with other windows in the
application until the modal window is dismissed.
✓ If an application has multiple modeless windows showing, the user
can switch between them at any time.
✓ Modality of a stage is defined by one of the following three
constants in the Modality enum in the javafx.stage package:
▪ Modality.NONE -- stage that does not block any other window.
▪ Modality.WINDOW_MODAL : a stage that blocks input events from
being delivered to all windows from its owner (parent) to its root. Its
root is the closest ancestor window without an owner.
▪ Modality.APPLICATION_MODAL : a stage that blocks input events
from being delivered to all windows from the same application, except
for those from its child hierarchy.
23
Cont..
✓ can set the modality of a stage using the initModality(Modality
m) method of the Stage class as follows:
Stage stage = new Stage();
stage.initModality(Modality.WINDOW_MODAL);
Stage Title and icon
✓ Image icon = new Image (getClass(). getResourceAsStream
("wdulogo.png"));
primaryStage.getIcons().add(icon);
primaryStage.setTitle(“Title”);
24
Cont..
Closing the Stage
setMaxHeight() methods of the Stage class let you set the range
within which the user can resize a stage. Calling the
setResizable(false) method on a Stage object prevents the user from
resizing the stage.
25
Cont..
✓ A stage may enter full-screen mode by calling the setFullScreen(true)
method.
about how to exit the full-screen mode: You will need to press the
ESC key to exit full-screen mode.
setFullScreen(false) method.
mode
26
Cont..
2. Scene
✓ The scene is the part of the stage that hosts the user interface of a
JavaFX application.
27
Cont..
Variables Type Description
28
The JavaFX Scene Graph API
✓ The first node in the tree is always called the root node,
30
Setting the Cursor for a Scene
✓ An instance of the javafx.scene.Cursor class represents a mouse
cursor.
✓ The Cursor class contains many constants, for example, HAND,
CLOSED_HAND, DEFAULT, TEXT, NONE, WAIT, for standard
mouse cursors. The following snippet of code sets the WAIT cursor
for a scene:
Scene scene;
scene.setCursor(Cursor.WAIT);
✓ A layout pane is a node that contains other nodes, which are known
as its children (or child nodes).
✓ The JavaFX SDK provides several layout panes for the easy setup
and management of classic layouts such as rows, columns, stacks,
and others.
✓ As a window is resized, the layout pane automatically repositions
and resizes the nodes that it contains according to the properties for
the nodes.
32
cont...
33
Pane layout
✓ A Pane provides the following layout features:
• It can be used when absolute positioning is needed. By default, it
positions all its children at (0, 0). You need to set the positions of
the children explicitly.
• It resizes all resizable children to their preferred sizes.
✓ The instances of the Pane class and its subclasses can add any
children.
Button okBtn = new Button("OK");
Button cancelBtn = new Button("Cancel");
Pane root = new Pane();
root.getChildren().addAll(okBtn, cancelBtn);
34
BorderPane
✓ The BorderPane layout pane provides five regions in
which to place nodes: top, bottom, left, right, and center.
✓ The regions can be any size.
35
working area in the center.
Cont..
✓ If the window is larger than the space needed for the contents of
each region, the extra space is given to the center region by
default.
✓ If the window is smaller than the space needed for the contents of
each region, the regions might overlap.
✓ The overlap is determined by the order in which the regions are
set.
✓ For example, if the regions are set in the order of left, bottom, and
right, when the window is made smaller, the bottom region
overlaps the left region and the right region overlaps the bottom
region.
36
Cont..
BorderPane bpane3 = new BorderPane(center, top, right, bottom, left)
37
HBox
✓ The Hbox layout pane provides an easy way for arranging a series
Example:
VBox vbox = new VBox(); // creating VBox
Text txt1= new Text(“Text 1");
Text txt2= new Text(“Text 2");
vbox.getChildren().addAll(txt1,
39 txt2); //adding buttons on the VBox
Cont..
40
StackPane
✓ The StackPane layout pane places all of the nodes within a single stack
✓ This layout model provides an easy way to overlay text on a shape or image
41
GridPane
✓ The GridPane layout pane enables you to create a flexible grid of rows and
✓ Nodes can be placed in any cell in the grid and can span cells as needed.
✓ A grid pane is useful for creating forms or any layout that is organized in
✓ Gap properties can be set to manage the spacing between the rows and
columns.
✓ The padding property can be set to manage the distance between the nodes
✓ The vertical and horizontal alignment properties can be set to manage the
42
alignment of individual controls in a cell.
Properties
The properties of the class along with their setter methods are
given in the table below.
Property Description Setter Methods
Represents the alignment of the grid
alignment setAlignment(Pos value)
within the GridPane.
43
Cont..
public class GridPaneDemo extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
GridPane root = new GridPane();
root.setPadding(new Insets(20));
root.setHgap(25);
root.setVgap(15);
Label labelTitle = new Label("Enter your user name and password!");
// Put on cell (0,0), span 2 column, 1 row.
root.add(labelTitle, 0, 0, 2, 1);
Label labelUserName = new Label("User Name");
TextField fieldUserName = new TextField();
Label labelPassword = new Label("Password");
PasswordField fieldPassword = new PasswordField();
Button loginButton = new Button("Login");
GridPane.setHalignment(labelUserName, HPos.RIGHT);
// Put on cell (0,1)
44
primaryStage.show();
root.add(labelUserName, 0, 1);
Cont..
GridPane.setHalignment(labelPassword, HPos.RIGHT);
root.add(labelPassword, 0, 2);
// Horizontal alignment for User Name field.
GridPane.setHalignment(fieldUserName, HPos.LEFT);
root.add(fieldUserName, 1, 1);
// Horizontal alignment for Password field.
GridPane.setHalignment(fieldPassword, HPos.LEFT);
root.add(fieldPassword, 1, 2);
// Horizontal alignment for Login button.
GridPane.setHalignment(loginButton, HPos.RIGHT);
root.add(loginButton, 1, 3);
wrap at the boundary set for the pane. Nodes can flow vertically (in
columns) or horizontally (in rows).
✓ A vertical flow pane wraps at the height boundary for the pane. A
horizontal flow pane wraps at the width boundary for the pane.
✓ Gap properties can be set to manage the spacing between the rows and
columns.
✓ The padding property can be set to manage the distance between the nodes
✓ The TilePane layout pane places all of the nodes in a grid in which each cell, or
tile, is the same size
✓ Nodes can be laid out horizontally (in rows) or vertically (in columns).
✓ Horizontal tiling wraps the tiles at the tile pane's width boundary and vertical
tiling wraps them at the height boundary.
✓ Use the prefColumns and prefRows properties to establish the preferred size
✓ Gap properties can be set to manage the spacing between the rows and columns.
✓ The padding property can be set to manage the distance between the nodes and the
47edges of the pane.
Javafx UI Controls
✓ Javafx UI controls are classes those resides in the javafx.scene.control
package of the JavaFX API.
• The below figure shows three common label usages. The label at the left is a
text element with an image, the label in the center represents rotated text,
and the label at the right renders wrapped text
50
Cont..
Creating Label
//An empty label
51
Cont..
You can add textual and graphical content by using the following
label
o setGraphic(Node graphic)– specifies the graphical icon
of the label.
52
Cont..
Adding an Icon and Text Fill to a Label
label1.setGraphic(new ImageView(image));
label1.setTextFill(Color.web("#0076a3"));
Applying Font Settings to a label
53
Button
Button class resides in the javafx.scene.control package of the JavaFX API enables
54
Cont..
Creating Button
55
Cont..
Because the Button class extends the Labeled class, you can use the
following methods to specify content for a button that does not have an
icon or text caption:
setText(String text) method – specifies the text caption for the button
56
button5.setGraphic(new ImageView(imageDecline));
Cont..
The default skin of the Button class distinguishes the visual states of the
button.
57
RadioButton
✓ RadioButton class resides in the javafx.scene.control package of the
JavaFX API.
✓ A radio button control can be either selected or deselected.
58
Cont..
Creating Radio Buttons
rb1.setText("Home");
59
Cont..
final ToggleGroup group = new ToggleGroup();
rb1.setToggleGroup(group);
rb1.setSelected(true);
rb2.setToggleGroup(group);
rb3.setToggleGroup(group);
60
CheckBox
✓ CheckBox class resides in the javafx.scene.control package of the
JavaFX API.
61
Cont..
Creating Checkboxes
cb1.setText("First");
cb1.setSelected(true);
62
ChoiceBox
✓ Choice Box class resides in the javafx.scene.control package of the JavaFX API.
✓ Choice Box control provides support for quickly selecting between a few options.
63
TextField
✓ The TextField class implements a UI control that accepts and displays text
input.
another text input control, PasswordField, this class extends the TextInput
class, a super class for all the text controls available through the JavaFX
API.
✓ Creating TextField
64
Cont.
✓ To defines the string that appears in the text field when the application is started
✓ Prompt captions notify users what type of data to enter in the text fields.
✓ The difference between the prompt text and the text entered in the text field is
that the prompt text cannot be obtained through the getText() method
65
Cont.
Some helpful methods that you can use with text fields.
66
PasswordField
The PasswordField class implements a specialized textfield. The characters
typed by a user are hidden by displaying an echo string.
passwordField.setPromptText("Your password");
67
ComboBox
✓ A combo box is a typical element of a user interface that enables users to choose
✓ A combo box is helpful when the number of items to show exceeds some limit,
because it can add scrolling to the drop down list, unlike a choice box.
✓ If the number of items does not exceed a certain limit, developers can decide
68
ComboBox
Creating a Combo Box with an Observable List
• At any time, you can supplement the list of items with new values.
.
• comboBox getValue() used to take selected value
69
DatePicker
• enables selection of a day rom the given calendar
• Creating date Picker
DatePicker datepicker= new DatePicker();
• datepicker.getValue() to take the selected date
70
Menu
• Menus are a standard way for desktop application to select options
71
Creating menu
//menu
Menu file= new Menu("File");
Menu edit= new Menu("Edit");
Menu insert= new Menu("Insert");
menubar.getMenus().addAll(file, edit,insert); // add menus on menu bar
// submenus
MenuItem newproject= new MenuItem("New Project");
MenuItem open= new MenuItem("Open Project");
Menu export= new Menu("Export to");
file.getItems().addAll(newproject, open, export); //add submenus to menu
// add menuItems to menu
export.getItems().addAll( new MenuItem("Excel"), new MenuItem("PDF"));
root.setTop(menubar); // add the menubar on the container
72
JavaFX 2D Shapes
JavaFX provides the flexibility to create our own 2D shapes on the screen
resides in javafx.scene.shape package.
A two dimensional shape is geometrical figure that can be drawn on the
coordinate system consist of X and Y planes
2D shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Cubic Curve,
quad curve, Arc, et
Example 1, Rectangele
Rectangle rect = new Rectangle()
rect.setX(20); //setting the X coordinate of upper left //corner of rectangle
rect.setY(20); //setting the Y coordinate of upper left //corner of rectangle
rect.setWidth(100); //setting the width of rectangle
rect.setHeight(100); // setting the height of rectangle
73
Example 2
Circle circle = new Circle();
circle.setCenterX(200);
circle.setCenterY(200);
circle.setRadius(100);
circle.setFill(Color.RED);
Example 3 :
Line line = new Line(); //instantiating Line class
line.setStartX(0); //setting starting X point of Line
line.setStartY(0); //setting starting Y point of Line
line.setEndX(100); //setting ending X point of Line
line.setEndY(200); //setting ending Y point of Line
74
Group Assignment
1) JavaFX Charts 1
2) Media with JavaFX 6
3) JavaFX 3D Shapes 8
4) JavaFX 3D Shapes 4
5) JavaFX Effects 3
6) JavaFX Charts 5
7) JavaFX Transformation 2
8) JavaFX Animation 7
75
Event Handling
✓ An event is an occurrence of a user interaction with the application.
✓ Clicking the mouse and pressing a key on the keyboard are examples of
events
• An event source:-The source from which the event is generated will be the
source of the event. i.e. mouse is the source of the even
• An event target: The node on which an event occurred. A target can be a
window, scene, and a node.
• An event type: Type of the occurred event; in case of mouse event – mouse
76
pressed, mouse released are the type of events.
Contt..
✓ The piece of code that is executed in response to an event is known as
✓ The event target is the destination of an event. The event target determines the
route through which the event travels during its processing. Suppose a mouse
click occurs over a Circle node. In this case, the Circle node is the event target of
the mouse-clicked event.
77
Contt..
✓ The event type describes the type of the event that occurs. for example,
✓ An input event indicates a user input (or a user action), for example,
clicking the mouse, pressing a key, touching a touch screen, and so forth.
JavaFX supports many types of input events.
✓ Below Figure shows the class diagram for some of the classes that
78
Contt..
79
Register event handler
▪ To add an event handler to a node, use the method
addEventHandler() of the Node class
EventHandler<MouseEvent> eventHandler =
new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
//Adding the event handler
btn.addEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);
To remove an event use removeEventHandler();
btn.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);
80
Register event Filter
▪ Use addEventFilter() of the Node class
//Creating the mouse event handler
Example: EventHandler<MouseEvent> eventHandler = new
EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println("Hello World");
circle.setFill(Color.DARKSLATEBLUE);
}
};
btn.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
▪ Mouse event types can be MOUSE_CLICKED, MOUSE_ENTERED,
MOUSE_PRESSED etc.
81
Styling nodes
✓ styling a node means decorating or make different from the
default appearance, this my done using javaFx or CSS codes.
✓ JavaFX allows you to define the look (or the style) of JavaFX
✓ To embed the CSS styling code in to the javaFx code have two
methods.
Those are Inline styling and External styling
82
cont..
✓ using external styling you can add multiple style sheets to a JavaFX
application.
✓ Style sheets are added to a scene or parents. Like
Scene scene = ...
scene.getStylesheets().add(javaFileName.class.getResource(“ss1.css").t
oExternalForm());
//Add a style sheet, vbox.css, to a VBox (a Parent)
VBox root = new VBox();
root.getStylesheets().add("vbox.css");
✓ ss1.css and vbox.css are css files that containe stayle of the
node of javaFx application.
83
cont..
.button {
-fx-background-color: red;
-fx-text-fill: white;
}
✓ The Node class has a style property that is of String Property
type.
✓ The style property holds the inline style for a node.
✓ can use the setStyle(String inlineStyle) and getStyle() methods
to set and get the inline style of a node
84
JavaFX CSS properties
-fx-background-color -fx-font-weight
-fx-background-image -fx-max-height
-fx-background-radius -fx-max-width
-fx-background-repeat -fx-text-fill
-fx-font-size -fx-border-color
-fx-background-radius: 50px; -fx-padding
85
Cont..
Styling a Button
.button1{
-fx-font: 22 arial;
-fx-base: #b6e7c9;
button1.getStyleClass().add("button1");
86
Example 1: File name mystyle.css
.button { .label { -fx-font-size: 16px;}
-fx-text-fill: white; .container
-fx-font-family: "Arial";
{ -fx-padding: 10px }
-fx-font-size: 14px;
#myButton { -fx-background-
-fx-padding: 10px 20px;
color: #007bff;}
-fx-border-color: #0056b3;
#mytextField{
-fx-border-width: 2px;
-fx-text-fill: red;
-fx-border-radius: 5px;
-fx-effect: dropshadow(three-pass-box, -fx-min-height: 100;
#000000, 10, 0.5, 0, 0); -fx-font-size: 50;
-fx-opacity: 0.9; }
-fx-cursor: hand; #lbl{
}
-fx-text-fill: green;
-fx-font-size: 50;
}
87
Example 1: File name Main.java
public class Main extends Application { tfName.setStyle("-fx-background-
public static void main(String[] args) color:yellow; -fx-border-color: blue");
{ vb.getChildren().addAll(name, tfName,
launch(args); button);
} Scene sc= new Scene(vb, 300, 300);
public void start(Stage stage) { sc.getStylesheets().add(getClass().
VBox vb= new VBox(); getResource("mystyle.css").toExternal
Label name= new Label("First Name"); Form());
name.setId("lbl"); vb.getStyleClass().add("container");
TextField tfName= new TextField(); vb.setSpacing(20);
Button button = new Button("Click Me");
stage.setScene(sc);
button.setId("myButton");
tfName.setId("mytextField"); stage.setTitle("First example");
stage.show();
}
}
88
??
The End
89