You are on page 1of 179



POUL KLAUSEN

JAVA 14: DEVELOPMENT


OF APPLICATIONS
WITH JAVAFX
SOFTWARE DEVELOPMENT

2
Java 14: Development of applications with JavaFX: Software Development
1st edition
© 2018 Poul Klausen & bookboon.com
ISBN 978-87-403-2188-3
Peer review by Ove Thomsen, EA Dania

3
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 

CONTENTS
Foreword 7

1 Introduction 9
1.1 HelloFX 9
1.2 HelloLines 16

2 Architecture of JavaFX 19
Exersice 1 21

3 2D Shapes 23
Exercise 2 24
Exercise 3 24
Exercise 4 25
Exercise 5 26
Exercise 6 26
Exercise 7 27

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

4
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 

Exercise 8 27
Exercise 9 28
Exercise 10 29
Exercise 11 29
3.1 SVG 30
Exercise 12 33
3.2 A Path 34
Exercise 13 36
Exercise 14 36
3.3 Shape properties 37
Exercise 15 42
3.4 Shape operations 42

4 Text 44

5 Effects 48
Problem 1 52
5.1 Colors 52
5.2 Images 56
5.3 Light 62
Problem 2 66

6 Transformations 70
Exercise 16 72
Exercise 17 72
Exercise 18 73
6.1 Animations 73
Exercise 19 76
Exercise 20 77
Exercise 21 77
Exercise 22 78
Exercise 23 79
Exercise 24 79

7 Components 80
7.1 Layout 80
7.2 Events 93
7.3 Components 106
Exercise 25 108
Exercise 26 108
Exercise 27 109
Exercise 28 110

5
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 

Problem 3 111
Exercise 29 112
Exercise 30 112
Exercise 31 113
Exercise 33 114
Exercise 34 115
Problem 4 115
Exercise 35 118
Exercise 36 119
7.4 Dialogs 120

8 Styling 131
Exercise 37 137

9 FXML 138
9.1 Create objects 144
9.2 DialogFXML 152
9.3 About FXML 160

10 A final example 162


10.1 Development 162

6
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 

FOREWORD
This book is the fourteenth in a series of books on software development and deals with
JavaFX. The book introduces JavaFX as an alternative to Swing and Java2D, thus treating
how to work with 2D graphics in JavaFX, as well as the main components and layout.
The goal is that you will quickly be able to write programs with a graphical user interface
using JavaFX. There are many topics, especially JavaFX properties, which the book does
not include, but these topics are dealt with in the following book. JavaFX is intended as
an alternative to Swing, and it is especially for better graphics and other media used in the
user interface. With JavaFX, it is easier to develop applications with a modern user interface
and with all the possibilities that users expect and get used to from web applications. The
book does not require the reader to know Swing and Java2D in detail, but assumes that the
reader has an introductory knowledge of developing programs with a graphical user interface.

As the title says this series of books deals with software development, and the goal is to
teach the reader how to develop applications in Java. It can be learned by reading about
the subject and by studying complete sample programs, but most importantly by yourself
to do it and write your own programs from scratch. Therefore, an important part of the
books is exercises and problems, where the reader has to write programs that correspond to
the substance being treated in the books. All books in the series is built around the same
skeleton and will consist of text and examples and exercises and problems that are placed
in the text where they naturally belongs. The difference between exercises and problems is
that the exercises largely deals with repetitions of the substance that is presented in the text,
and furthermore it is relatively accurately described what to do. Problems are in turn more
loosely described, and are typically a little bigger and there is rarely any clear best solution.
These are books to be read from start to finish, but the many code examples, including
exercises and problems plays a central role, and it is important that the reader predict in
detail studying the code to the many examples and also solves the exercises and problems
or possibly just studying the recommended solutions.

All books ends with one or two larger sample programs, which focus primarily is on process
and an explanation of how the program is written. On the other hand appears the code only
to a limited extent - if at all - and the reader should instead study the finished program
code perhaps while testing the program. In addition to show the development of programs
that are larger than the examples, which otherwise is presented, the aim of the concluding
examples also is to show program examples from varying fields of application.

Most books also ends with an appendix dealing with a subject that would not be treated
in the books. It may be issues on the installation of software or other topics in computer

7
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 

technology, which are not about software development, but where it is necessary to have
an introductory knowledge. If the reader already is familiar with the subject, the current
appendix can be skipped.

The programming language is, as mentioned Java, and besides the books use the following
products:

1. NetBeans as IDE for application development


2. MySQL to the extent there is a need for a database server (from the book Java 6
onwards)
3. GlassFish as a web server and application server (from the book Java 11 onwards)

It is products that are free of charge and free to install, and there is even talk about products,
where the installation is progressing all by itself and without major efforts and challenges.
In addition, there are on the web detailed installation instructions for all the three products.
The products are available on Windows and Linux, and it therefore plays no special role if
you use Linux or Windows.

All sample programs are developed and tested on machines running Linux. In fact, it plays
no major role, as both Java and other products work in exactly the same way whether the
platform is one or the other. Some places will be in the books where you could see that
the platform is Linux, and this applies primarily commands that concerning the file system.
Otherwise it has no meaning to the reader that the programs are developed on a Linux
machine, and they can immediately also run under Windows unless a program refers to
the file system where it may be necessary to change the name of a file.

Finally a little about what the books are not. It is not "how to write" or for that matter
reference manuals in Java, but it is as the title says books on software development. It is
my hope that the reader when reading the books and through the many examples can find
inspiration for how to write good programs, but also can be used as a source collection
with a number of examples of solutions to concrete everyday programming problems that
you regularly face as a software developer.

8
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Introduction

1 INTRODUCTION
In the books Java 2, Java 9 and primarily Java 10, I have dealt with how to write a standalone
Java application with a graphical user interface. All of it has been based on Swing, which
is an API that makes the necessary available through a comprehensive class library. There is
nothing wrong with Swing, and it will be there many years to come, among other things
because there are a lot of programs based on Swing. However, there are alternatives and one
of them is called JavaFX, as the new API for developing Java applications with a graphical
user interface.

JavaFX is intended as an alternative to Swing, and it is especially for better graphics and
other media used in the user interface. With JavaFX, it is easier to develop applications
with a modern user interface and with all the possibilities that users expect and get used to
from web applications. However, it is important to emphasize that you can still use Swing
components, so that all known facilities from Swing are still available.

JavaFX is an alternative to Swing, but the idea actually originates from World Wide Web,
where you can build the user interfaces using markup, and to a large extent you can design
the applications user interface using styles. The goal of this book is to show how to use
JavaFX, and I will alone look at the development of standalone applications, but the goal
of JavaFX is also the development of the client side of web application, which means that
a JavaFX application can be opened as

4. a standalone desktop application


5. with the Java Web Start tecnology
6. as a part of a web page

For the time being, I will only look at the first option.

1.1 HELLOFX
As a start, I will show a very simple application that opens a window with a few buttons
and a little more, but a program that uses JavaFX instead of Swing. I start with a new
project in Netbeans, but it must be a JavaFX Application project. I have called the project
HelloFX, and after the project has been created, NetBeans has created a single class (where
I have removed all comments):

9
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX:
WITH 14: DEVELOPMENT
SOFTWAREOF APPLICATIONS
DEVELOPMENT Introduction
WITH JAVAFX: SOFTWARE DEVELOPMENT IntroduCtIon

package hellofx;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class HelloFX extends Application


{
@Override
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 World!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args)


{
launch(args);
}
}

In
In fact,
fact, itit isis aa fully
fully finished
finished program,
program, and
and starting
starting the
the program
program opens
opens the
the following
following window:
window:

10
8
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Introduction

and clicking on the button it prints a message on the console. If you consider the code, first
notice that the class inherits Application, which means that it is a JavaFX application. The
class has a usual main() method as other Java applications, and it starts by calling a static
method launch() (in the class Application). It basically performs the following:

1. instantiates an object of the class (here the class HelloFX)


2. performs a method init(), which in Application is an empty method
3. performs a method start(), which in Application is an empty method
4. waiting until the program terminates, where method stop(), as in Application is an
empty method, is performed

If you want an application to open a window, it usually happens to override the method
start() from the class Application, as is the case in the above example.

A JavaFX program basically consists of a Stage object that contains a Scene object, which
again contains Node objects arranged in a tree. A Stage object represents a window and
the primary Stage object is created by the runtime system and is sent as a parameter to
the method start(), and in the above example it has the name primaryStage. A Scene object
contains all of the window’s objects organized into a tree called a scene graph. The tree’s
elements are Node objects, and a node can be an branch node (which has children) or a
leaf node (which no children have). A node is a component in the window and may, for
example, be a button or an entry field.

In the example above, the method start() begins by creating a button, which is a node. The
object is called btn, and besides attaching a text to the button, an action is also associated,
which is an object with a single method, which simply performs a System.out.println(). You
should note that it looks like a usual event handling as it is known from Swing, but it is
not the case, and other types are used, although they have the same names as some of the
known types from Swing.

11
JAVA 14:
JAVA 14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH JAVAFX:
WITH JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT IntroduCtIon
Introduction

As aa next
As next step,
step, aa root
root object
object ofof the
the type
type StackPane
StackPane isis created,
created, and
and itit isis the
the root
root ofof the
the scene
scene
graph and
graph and the
the button
button isis inserted
inserted asas aa child
child to
to root.
root. This
This program
program thus thus hashas aa very
very simple
simple
scene graph
scene graph consisting
consisting of of aa root
root and
and aa single
single leaf
leaf node.
node. The
The root
root object
object isis then
then added
added toto aa
Sceen object,
Sceen object, which
which represents
represents thethe window’s
window’s content,
content, while
while defining
defining the the window
window size.size. This
This
Scene object
Scene object must
must bebe attached
attached toto the
the Stage
Stage object,
object, which
which isis also
also assigned
assigned aa title,title, and
and finally,
finally,
the method
the method show()
show() isis performed
performed on on the
the object
object primaryStage,
primaryStage, which
which displays
displays the the window
window on on
the screen.
the screen.

It isis thus
It thus easy
easy to
to follow
follow what
what happens
happens in in the
the above
above program,
program, but but itit isis more
more difficult
difficult to
to spot
spot
the benefits.
the benefits. They
They come
come later,
later, but
but II can
can immediately
immediately point
point outout that
that one one of
of the
the advantages
advantages
isis that
that the
the technology
technology used
used to
to draw
draw the
the window
window with
with all
all its
its content
content isis extremely
extremely effective.
effective.

Before II leave
Before leave this
this example,
example, II will
will change
change the
the code
code aa bit
bit (for
(for now,
now, the
the code
code appears
appears as
as
NetBeans has
NetBeans has created
created it).
it). II have
have changed
changed the
the code
code to
to the
the following:
following:

package hellofx;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.application.Platform;

public class HelloFX extends Application


{
@Override
public void start(Stage stage)
{
System.out.println("Start " + Thread.currentThread().getId());
TextField txtName = new TextField();
Label lblText = new Label();
lblText.setStyle("-fx-text-fill: blue;");
Button cmdHello = new Button("Hello");
cmdHello.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
String name = txtName.getText();
lblText.setText(name.trim().length() > 0 ? "Hello " + name :
"Hello there");

10
12
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Introduction
WITH JAVAFX: SOFTWARE DEVELOPMENT IntroduCtIon

}
});
VBox root = new VBox();
root.setSpacing(10);
root.getChildren().addAll(new Label("Enter your name:"), txtName, lblText,
cmdHello, createButton("Exit", e -> Platform.exit()));
stage.setScene(new Scene(root, 300, 200));
stage.setTitle("Hello FX");
stage.show();
}

private Button createButton(String text, EventHandler<ActionEvent> handler)


{
Button cmd = new Button(text);
cmd.setOnAction(handler);
return cmd;
}

public static void main(String[] args)


{
launch(args);
}

public HelloFX()
{
System.out.println("Constructor " + Thread.currentThread().getId());
}

@Override
public void init()
{
System.out.println("Init " + Thread.currentThread().getId());
}

@Override
public void stop()
{
System.out.println("Stop " + Thread.currentThread().getId());
}
}

If you run the program, it first writes the following lines on the console:

Constructor 12
Init 13
Start 12

13
11
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Introduction

after which you get the following window

If you enter the text Frode Fredegod and click Hello, the window will be updated to:

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

14
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA JAVAFX:
WITH 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Introduction
IntroduCtIon
WITH JAVAFX: SOFTWARE DEVELOPMENT IntroduCtIon

and
and clicking
clicking Exit
Exit terminates
terminates the
the program
program after
after writing
writing the
the following
following text
text on
on the
the console:
console:
and clicking Exit terminates the program after writing the following text on the console:

Stop 12
Stop 12

This time, the


This the method start()
start() creates aa scene
scene graph with
with a root that
that has 55 leaf
leaf nodes. Note
Note
This time,
time, the method
method start() creates
creates a scene graph
graph with aa root
root that has
has 5 leaf nodes.
nodes. Note
that the type
that type of root
root is VBox. There
There is no particular
particular justification inin addition toto showing that
that
that the
the type of
of root isis VBox.
VBox. There isis nono particular justification
justification in addition
addition to showing
showing that
there are more
there more options, and and the type
type is relevant to to how thethe graph’s nodes
nodes are laid
laid out in
in the
there are
are more options,
options, and the the type isis relevant
relevant to how
how the graph’s
graph’s nodes are
are laid out
out in the
the
window.
window. The 5 nodes have the types Label, TextField, Label, Button and Button, where the
window. The The 55 nodes
nodes have
have the
the types
types Label,
Label, TextField,
TextField, Label,
Label, Button
Button and
and Button,
Button, where
where the
the
first and the
first the last are
are created when
when they are are added to to root (the
(the last created
created of the
the method
first and
and the last
last are created
created when theythey are added
added to root
root (the last
last created of
of the method
method
createButton()),
createButton()), while the other three are created explicitly.
createButton()), while
while the
the other
other three
three are
are created
created explicitly.
explicitly.

Note that the


Note the method start()
start() starts by
by printing aa text
text (on the
the console). II have
have also overwritten
overwritten
Note that
that the method
method start() starts
starts by printing
printing a text (on(on the console).
console). I have also
also overwritten
the two methods
the methods init() and
and stop() so
so they both
both print aa text
text and finally
finally I have added
added a default
the two
two methods init()
init() and stop()
stop() so they
they both print
print a text andand finally II have
have added aa default
default
constructor.
constructor. They show that the constructor is first executed, then init() and finally start().
constructor. They
They show
show that
that the
the constructor
constructor isis first
first executed,
executed, then
then init()
init() and
and finally
finally start().
start().
Finally, they show
Finally, show that thethe method stop()
stop() is executed when when the program
program terminates. Here Here
Finally, they
they show that
that the method
method stop() isis executed
executed when the the program terminates.
terminates. Here
you should note
you note that the
the constructor, start()
start() and stop()
stop() are executed
executed in the the same thread
thread
you should
should note that
that the constructor,
constructor, start() and and stop() are are executed in in the same
same thread
(called the JavaFX
(called JavaFX Application Thread 
Thread ), while init()
init() is performed in in its own
own thread (called
(called
(called the
the JavaFX Application
Application Thread),), while
while init() isis performed
performed in its its own thread
thread (called
the JavaFX Launcher).
the Launcher).
the JavaFX
JavaFX Launcher).

If you
IfIf you look at at the directory
directory dist, youyou can seesee that aa jar
jar file named
named HelloFX.jar hashas been
you look
look at the
the directory dist,
dist, you can
can see that
that a jar file
file named HelloFX.jar
HelloFX.jar has been
been
created
created in the usual way, and the program can therefore be executed from the command
created in in the
the usual
usual way,
way, and
and the the program
program cancan therefore
therefore be
be executed
executed from
from the
the command
command
line
line as (if current directory is the folder dist):
line as
as (if
(if current
current directory
directory isis the
the folder
folder dist):
dist):

java -jar HelloFX.jar


java -jar HelloFX.jar

The directory dist also contains other files:


The directory dist also contains other files:
The directory dist also contains other files:

These files I do not want to mention in this place, but they all have to do with the execution
These files I do not want to mention in this place, but they all have to do with the execution
These
of thefiles I do not
program as awant
webtoapplication.
mention in this place, but they all have to do with the execution
of the program as a web application.
of the program as a web application.

15
13
13
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Introduction
IntroduCtIon

1.2 HELLOLINES
1.2 HELLOLINES
As
As another
another example
example of
of aa JavaFX
JavaFX program,
program, II will
will show
show an
an example
example that
that opens
opens the
the
following
following window:
window:

The
The project
project isis called
called HelloLines,
HelloLines, and
and the
the window
window contains
contains aa scene
scene graph,
graph, consisting
consisting of
of aa root
root
with
with 44 child
child nodes:
nodes: aa Text
Text object
object and
and three
three Line
Line objects.
objects. The
The code
code isis as
as follows:
follows:

package hellolines;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.stage.Stage;
import javafx.scene.shape.Line;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.Font;

public class HelloLines extends Application


{
private Line[] lines;

public HelloLines()
{
lines = new Line[] { createLine(20, 20, 320, 120, 3, Color.RED),
createLine(320, 120, 120, 220, 5, Color.GREEN),
createLine(120, 220, 20, 20, 1, Color.BLUE) };
}

private Line createLine(double x1, double y1, double x2, double y2,
double width, Color color)
{

16
14
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH14: DEVELOPMENT
JAVAFX: OF DEVELOPMENT
SOFTWARE APPLICATIONS Introduction
WITH JAVAFX: SOFTWARE DEVELOPMENT IntroduCtIon

Line line = new Line(x1, y1, x2, y2);


line.setStroke(color);
line.setStrokeWidth(width);
return line;
}

private Text createText()


{
Text text = new Text("Hello");
text.setX(200);
text.setY(50);
text.setFont(new Font(36));
return text;
}

@Override
public void start(Stage stage)
360°
.
{
Group root = new Group(lines);
root.getChildren().add(createText());
Scene scene = new Scene(root, 350, 250); thinking

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


17
15
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Introduction
WITH JAVAFX: SOFTWARE DEVELOPMENT IntroduCtIon

stage.setTitle("Triangle");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args)


{
launch(args);
}
}

When you see the code, it is easy enough to understand and looks like the first example.
The class defines an array of Line elements (a Line object represents a straight line), and
the array is created in the constructor so that it contains three Line objects. A Line object
is created using the method createLine(), in which you should especially note how an object
is initialized and what types are used. There is also a method createText(), which creates and
returns a Text object. If you consider the types used to create Line and Text objects, it is not
the same types that you know from Java2D, but they have the same names and basically
have the same characteristics. The scene graph is created in the same way as in the previous
example in the method start(), but this time the type of the root element is Group, which
is the basic type for a branch node. You should especially note how with getChildren() to
get a list with all child nodes.

The example is simple, but you should note how geometric objects and text elements are
included in the scene graph as nodes in the same way as other nodes such like Button,
Label, and more.

18
16
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Architecture of JavaFX

2 ARCHITECTURE OF JAVAFX
JavaFX is a full API for creating GUI applications and consists of classes distributed on
the following packages:

1. javafx.animation
2. javafx.application
3. javafx.css
4. javafx.event
5. javafx.geometry
6. javafx.stage
7. javafx.scene

where the latter has more sub packages. A JavaFX program consists as mentioned of a scene
graph, which is a tree containing nodes that may be

-- geometrical objects, that can be 2D and 3D objects, as Circle’s, Sphere’s and so on


-- UI controls, such as Label, Button and so on
-- Containers, as StackPane, VBox, Group and more
-- Media elements, for images, audio and video

Each node in a scene graph has a unique parent, except the root, which has no parent,
and all nodes that do not have child nodes are called as mentioned for leaf nodes, while all
other nodes are called branch nodes. The same node can only occur in the tree once, and
each node may have defined effects, opacity, transforms, and event handlers.

To render the graphics JavaFX uses openGL (on Linux systems) and, as far as possible, use
the graphics card’s hardware accelerator with the result that JavaFX is highly effective in
rendering graphics.

As mentioned above, a JavaFX application is represented by a Stage object that contains all
of the application’s objects, and the Stage object is created by the actual platform. A Stage
object has a width and a height in addition to the content (the scene graph), and there are
decorations as a title line and a frame. There are the following kind of Stage objects:

19
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Architecture of JavaFX

-- Decorated
-- Undecorated
-- Transparent
-- Unified
-- Utility

and the individual objects are discussed continuously in connection with the examples.

The Stage object’s content is represented by a Scene object, which defines the width and
height as well as the scene graph. The individual nodes are discussed in connection with
the examples, and there are many with each there purpose. Among other things, there are
different branch nodes, where the simplest is a Group node, which is primarily a collection
of child nodes. Other examples are Pane nodes with several specific derivative classes, which
play the same role as layout managers in Swing. All the specific nodes are part of a hierarchy
of class’s and are derived from one of the following classes:

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

20
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Architecture of JavaFX

EXERSICE 1
You must write a JavaFX application that opens the following window, where there are two
entry fields at the top and at the bottom of a list box:

If you click the Add button, (and something has been entered in both fields), a line must
be inserted in the list box where the name and title are separated by comma. If you click
on the other button, the content of the list box must be deleted. It is a requirement that
the size of the two input fields as well as the size of the list box follows the size of the
window and that the buttons follow the edge of the window.

21
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Architecture of JavaFX

Below is the window after 6 people have entered. Note that it is a part of the task to find
out which controls are to be used and how to place them in the window:

22
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

3 2D SHAPES
In this chapter I will review how to draw geometric shapes in a window, and as may be
seen in the last example of chapter 1, it is almost the same as in Java2D, only other classes
are used. A geometric shape is an object of the type Shape2D, and thus an object that is a
node and can be included in a scene graph. Generally, there are the following predefined
shapes (nodes):

-- Line
-- Rectangle
-- Circle
-- Ellipse
-- Polygon
-- Polyline
-- CubicCurve
-- QuadCurve
-- Arc

In addition, you can define general curves as Path objects consisting of segments of the types:

-- Line
-- CubicCurve
-- QuadCurve
-- Arc

and finally you can define a shape like a SVG Path.

The aim of this chapter is to show how to create and apply the above geometric shapes,
but instead of reviewing the syntax (which is a lot about what you know from Java2D), I
will instead formulate a series of exercises where the challenge is primarily to find out of
what the types are called JavaFX.

23
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

EXERCISE 2
Write a JavaFX application that opens the following window:

The blue line has the endpoints (20, 20) and (320, 20) and width 21, while the red line has
the endpoints (20, 40) and (320, 40) and width 1. Finally, the green line has the endpoints
(20, 60) and (320, 60) and width 21.

EXERCISE 3
Write a JavaFX program that opens the following window:

which shows three rectangles, each of which has a size of 300 × 50. The left upper corner
of the three rectangles are (20, 20), (20, 90) and (20, 160) respectively. The top has a blue
frame with a width of 21, but an empty inner. The middle has no frame, while the latter
has a black frame with the width 1.

24
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

EXERCISE 4
Write a program that shows a window with three rectangles with rounded corners:

Note that JavaFX does not have a type for rectangles with rounded corners, and the shapes
are of the type Rectangle.

AXA Global
Graduate Program
Find out more and apply

25
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

EXERCISE 5
Write a JavaFX program that opens the following window:

when the type of the shapes must be Circle.

EXERCISE 6
Write a program that opens the following window:

where the type of the three shapes are Ellipse.

26
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

EXERCISE 7
A polygon is a closed shape bounded by straight lines, and you defines a polygon by
specifying the coordinates of the corners. Write a JavaFX program that opens the following
window, which shows three polygons:

EXERCISE 8
A polyline is defined as a polygon and consists of straight lines. The shape is defined
in the same way as a sequence of corners, but there is no need to be a coherent shape.
Generally, a polyline is not a filled shape, but if you define a fill color, the shape is filled
as a polygon. In this exercise, you must write a program that opens the following window
with 4 polyline shapes:

27
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

EXERCISE 9
You must write a program that shows two quad curves. If you do not remember the definition
of a quad curve, you might want to read about the curve in the book Java 10. The program
must open the following window:

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

28
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

EXERCISE 10
You must write a program that shows two cubic curves. If you do not remember the definition
of a cubic curve, you might want to read about the curve in the book Java 10. The program
must open the following window:

EXERCISE 11
Write a program that opens the window below, showing 6 circle/ellipse slices. All slices start
at 0 and span over an angle of 60 degrees. The top three are circle sections from a circle
with radius 100, while the three bottom are slices of an ellipse with radiuses 200 and 100:

29
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

3.1 SVG
SVG stands for Scalable Vector Graphics, and in relation to JavaFX, you define a shape in
the form of a path as a string containing commands. There are the following commands
where the cursor denotes the drawing tool:

1. M or m, which means move to. As a result, the cursor is moved to the following
coordinate. Is the command M, the coordinates designate an absolute position,
and is the command m, the coordinates denote a relative position. If you indicate
more coordinates, they are perceived as multiple subsequent move to operations.
2. Z or z, which means close and closes the path with a straight line from the current
position of the cursor to the start of the curve.
3. L or 1, which means line to. As a result, the cursor draws a straight line from the
current point to the subsequent coordinate. If the command is L, the coordinates
denote an absolute position and is the command l, the coordinates denote a relative
position. If you indicate more coordinates, they are perceived as several subsequent
line to operations.
4. H or h, which means horizontal to. As a result, the cursor draws a horizontal line
from the current point to the following x-coordinate. Is the command H, the
coordinates designate an absolute position and is the command h, the coordinates
denote a relative position. If you specify multiple x coordinates, they are perceived
as multiple subsequent horizontal to operations.
5. V or v, which means vertical to. As a result, the cursor draws a vertical line from the
current point to the following y coordinate. If the command is V, the coordinates
denote an absolute position and is the command v, the coordinate denotes a
relative position. If you specify more y coordinates, they are perceived as multiple
subsequent vertical to operations.
6. C or c, which means cubic to. As a result, the cursor draws a cubic curve from the
current point to the last of the following three coordinate pairs. The first two are
control points. Is the command C, the coordinates designate an absolute position,
and is command c, the coordinates denote a relative position. If you specify more
coordinate sets, they are perceived as several subsequent curve to operations.
7. Q or q, which means quad to. As a result, the cursor draws a quad curve from
the current point to the last of the following two coordinate pairs. The first is the
control point. Is the command Q, the coordinates designate an absolute position
and is the command q, the coordinates denote a relative position. If you specify
more coordinate sets, they are perceived as several subsequent quad to operations.
8. A or a, which means arc to. The result is that the cursor draws an arc starting in the
current point to (x, y). The parameters are (rx row rotation large sweep x y), where rx
and row are radii in an ellipse and rotation is the ellipse rotation about the x-axis.
The two parameters large and sweep indicate which of the two arcs to be selected,

30
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

and the center of the ellipse is calculated automatically from the parameters. Is the
command A, the coordinates designate an absolute position and is the command
a, the coordinates denote a relative position. If you specify more parameter sets,
they are perceived as several subsequent arc to operations.

As an example, below is shown an application that opens the following window:

which shows two shapes, both of which have the type SVGPath. Both shapes are drawn
with two line to commands and an arc to command. The code is as follows:

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

31
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX:
WITH 14: DEVELOPMENT
SOFTWAREOF APPLICATIONS
DEVELOPMENT 2D Shapes
WITH JAVAFX: SOFTWARE DEVELOPMENT 2d shApes

package svgprogram;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.*;
import javafx.stage.Stage;
import javafx.scene.shape.*;
import javafx.scene.paint.*;

public class SVGProgram extends Application


{
@Override
public void start(Stage primaryStage)
{
Group root = new Group();
root.getChildren().add(path1());
root.getChildren().add(path2());
Scene scene = new Scene(root, 500, 150);
primaryStage.setTitle("SVG");
primaryStage.setScene(scene);
primaryStage.show();
}

private SVGPath path1()


{
SVGPath path = new SVGPath();
path.setContent("M 20 120 L 70 20 120 120 A 100 100 0 0 0 20 120");
path.setStroke(Color.BLUE);
path.setStrokeWidth(3);
path.setFill(null);
return path;
}

private SVGPath path2()


{
SVGPath path = new SVGPath();
path.setContent("M 220 120 L 270 20 320 120 A 100 100 0 0 1 220 120");
path.setStroke(Color.BLUE);
path.setStrokeWidth(3);
path.setFill(Color.YELLOW);
return path;
}

public static void main(String[] args)


{
launch(args);
}
}

32
30
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

Here is the interesting of course the two SVG commands. You must note the syntax and
how the commands are simply defined as a list separated by spaces. The only thing that is
not obvious is command A, which defines an arc. In this case, it is (in the first case) a curve
from (120, 120) to (20, 120) in a circle of radius 100 and it offers two options:

Which one chooses is determined by the two parameters large and sweep (whose values are
0 or 1).

EXERCISE 12
Write a program that opens the following window, which shows two SVGPath shapes where
the blue curve consists of a move to, two line to and an arc to operation, while the red
consists of one quad to, two line to, one cubic to and a close operation:

33
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

3.2 A PATH
Instead of drawing a path as shown above, where you defines the drawing operations as a
string, you can add drawing objects to a Path object that represents a collection of drawing
objects. The advantage is primarily that the compiler can check the syntax and that any
errors are thus detected before runtime. There are the following drawing objects:

-- MoveTo
-- LineTo
-- HLineTo
-- VLineTo
-- ArcTo
-- QuadCurveTo
-- CubicCurveTo

34
JAVA 14:
JAVA 14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH JAVAFX:
WITH JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT 2d Shapes
2D shApes

For example,
For example, the
the following
following program
program draws
draws the
the same
same window
window as
as shown
shown in
in the
the previous
previous
example:
example:

package pathprogram;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.*;
import javafx.stage.Stage;
import javafx.scene.shape.*;
import javafx.scene.paint.*;

public class PathProgram extends Application


{
@Override
public void start(Stage primaryStage)
{
Group root = new Group();
root.getChildren().add(path1());
root.getChildren().add(path2());
Scene scene = new Scene(root, 500, 150);
primaryStage.setTitle("Paths");
primaryStage.setScene(scene);
primaryStage.show();
}

private Path path1()


{
Path path = new Path();
path.getElements().add(new MoveTo(20, 120));
path.getElements().addAll(new LineTo(70, 20), new LineTo(120, 120));
path.getElements().add(new ArcTo(100, 100, 0, 20, 120, false, false));
path.setStroke(Color.BLUE);
path.setStrokeWidth(3);
path.setFill(null);
return path;
}

private Path path2()


{
Path path = new Path();
path.getElements().addAll(new MoveTo(220, 120), new LineTo(270, 20),
new LineTo(320, 120), new ArcTo(100, 100, 0, 220, 120, false, true));
path.setStroke(Color.BLUE);
path.setStrokeWidth(3);
path.setFill(Color.YELLOW);
return path;
}

33
35
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS 2D Shapes
WITH JAVAFX: SOFTWARE DEVELOPMENT 2d shApes

public static void main(String[] args)


{
launch(args);
}
}

In
In fact,
fact, there
there is
is not
not much
much to
to explain,
explain, but
but you
you should
should notice
notice how
how to
to create
create aa Path
Path object
object
and
and how to add drawing objects. Also note how to create each drawing object, and that
how to add drawing objects. Also note how to create each drawing object, and that
the objects are used in the order as they are added to the Path object.
the objects are used in the order as they are added to the Path object.

EXERCISE
EXERCISE 13
13
You
You must
must write
write aa program
program that
that opens
opens the
the same
same window
window as
as in
in exercise
exercise 12,
12, but
but this
this time
time the
the
type of the two shapes must be a Path.
type of the two shapes must be a Path.

EXERCISE
EXERCISE 14
14
Write
Write aa program
program that
that opens
opens the
the following
following window
window when
when the
the shape
shape should
should be
be aa Path
Path object:
object:

36
34
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

3.3 SHAPE PROPERTIES


The above has primarily concerned the shape of figures like straight lines, rectangles, circles,
and more, but there are also some other properties attached to shapes, including how they
are filled and how the perimeter is drawn. This section will discuss the most important of
these features.

The perimeter – which is a line / curve – can be drawn in three ways:

1. StrokeType.CENTERED, which is default and means the perimeter is drawn so that


the edge of the shape is exactly the center of the perimeter line.
2. StrokeType.INSIDE, where the perimeter is drawn as it falls within the shape.
3. StrokeType.OUTSIDE, where the perimeter is drawn outside the shape.

The program StrokeProgram opens the following window, which illustrates the three ways
to draw the perimeter and where the first is the default:

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

37
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT 2D
2d Shapes
shApes

The
The code
code isis the
the following,
following, where
where II have
have only
only shown
shown the
the method
method start():
start():

public void start(Stage primaryStage)


{
Group root = new Group();
root.getChildren().add(circ1());
root.getChildren().add(circ2());
root.getChildren().add(circ3());
Scene scene = new Scene(root, 500, 250);
primaryStage.setTitle("Strokes");
primaryStage.setScene(scene);
primaryStage.show();
}

private Circle circ1()


{
Circle circ = new Circle(80, 120, 50, Color.RED);
circ.setStroke(Color.BLUE);
circ.setStrokeWidth(21);
circ.setStrokeType(StrokeType.CENTERED);
return circ;
}

private Circle circ2()


{
Circle circ = new Circle(220, 120, 50, Color.RED);
circ.setStroke(Color.BLUE);
circ.setStrokeWidth(21);
circ.setStrokeType(StrokeType.INSIDE);
return circ;
}

36
38
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX:
JAVA
WITH 14: DEVELOPMENT
14: DEVELOPMENT
SOFTWAREOF
OF APPLICATIONS
APPLICATIONS
DEVELOPMENT 2D Shapes
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT 2d
2d shApes
shApes

private Circle circ3()


{
Circle circ = new Circle(360, 120, 50, Color.RED);
circ.setStroke(Color.BLUE);
circ.setStrokeWidth(21);
circ.setStrokeType(StrokeType.OUTSIDE);
return circ;
}

Another thing
Another thing isis the
the endpoints
endpoints of
of the
the line
line and
and here
here especially
especially for
for shapes
shapes composed
composed of
of
straight lines,
straight lines, such
such asas polygons.
polygons. There
There are
are three
three options
options (as
(as you
you also
also know
know from
from Java2D):
Java2D):

1. StrokeLineJoin.MITTER
1. StrokeLineJoin.MITTER which
which isis default
default
2. StrokeLineJoin.BEVEL
2. StrokeLineJoin.BEVEL
3. StrokeLineJoin.ROUND
3. StrokeLineJoin.ROUND

You can
You can find
find the
the exact
exact explanation
explanation of
of how
how these
these endpoints
endpoints are
are calculated
calculated in
in the
the book
book about
about
Java2D. The
Java2D. The application
application JoinProgram
JoinProgram opens
opens the
the following
following window,
window, which
which shows
shows the
the effect
effect
of each
of each of
of the
the three
three options:
options:

public void start(Stage primaryStage)


{
Group root = new Group();
root.getChildren().add(poly1());
root.getChildren().add(poly2());
root.getChildren().add(poly3());
root.getChildren().add(poly4());
root.getChildren().add(poly5());
root.getChildren().add(poly6());
Scene scene = new Scene(root, 550, 210);
primaryStage.setTitle("Triangles");
primaryStage.setScene(scene);
primaryStage.show();
}

39
37
37
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX:
WITH 14: DEVELOPMENT
SOFTWAREOF APPLICATIONS
DEVELOPMENT 2D Shapes
WITH JAVAFX: SOFTWARE DEVELOPMENT 2d shApes

private Polygon poly1()


{
Polygon poly = new Polygon(30, 30, 150, 90, 30, 150);
poly.setStroke(Color.BLUE);
poly.setStrokeWidth(21);
poly.setFill(null);
poly.setStrokeLineJoin(StrokeLineJoin.MITER);
return poly;
}

private Polygon poly2()


{
Polygon poly = new Polygon(210, 30, 330, 90, 210, 150);
poly.setStroke(Color.BLUE);
poly.setStrokeWidth(21);
poly.setFill(null);
poly.setStrokeLineJoin(StrokeLineJoin.BEVEL);
return poly;
}

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

40
38
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX:
WITH 14: DEVELOPMENT
SOFTWAREOF APPLICATIONS
DEVELOPMENT 2D Shapes
WITH JAVAFX: SOFTWARE DEVELOPMENT 2d shApes

private Polygon poly3()


{
Polygon poly = new Polygon(390, 30, 510, 90, 390, 150);
poly.setStroke(Color.BLUE);
poly.setStrokeWidth(21);
poly.setFill(null);
poly.setStrokeLineJoin(StrokeLineJoin.ROUND);
return poly;
}

private Polygon poly4()


{
Polygon poly = new Polygon(30, 30, 150, 90, 30, 150);
poly.setStroke(Color.BLACK);
poly.setStrokeWidth(1);
poly.setFill(null);
return poly;
}

private Polygon poly5()


{
Polygon poly = new Polygon(210, 30, 330, 90, 210, 150);
poly.setStroke(Color.BLACK);
poly.setStrokeWidth(1);
poly.setFill(null);
return poly;
}

private Polygon poly6()


{
Polygon poly = new Polygon(390, 30, 510, 90, 390, 150);
poly.setStroke(Color.BLACK);
poly.setStrokeWidth(1);
poly.setFill(null);
return poly;
}

There
There are
are similar
similar options
options for
for specifying
specifying endpoints
endpoints of
of lines
lines (please
(please check
check the
the book
book Java
Java 10
10
for an explanation):
for an explanation):

1.
1. StrokeLineCap.BUTT
StrokeLineCap.BUTT
2. StrokeLineCap.SQUARE
2. StrokeLineCap.SQUARE
3.
3. StrokeLineCap.ROUND
StrokeLineCap.ROUND

41
39
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT 2D Shapes

EXERCISE 15
Write a program that you can call LineCaps. The program must open the following window,
which shows 6 Line objects (each of which has a length of 200), and each endpoint (of the
blue lines) is BUTT, SQUARE and ROUND respectively:

3.4 SHAPE OPERATIONS


In general, if you add two Shape objects to a Group and the two shapes overlap, then the
shape added last will cover the part of the first shape that overlaps. The Shape class has
three static methods

-- union()
-- intersect()
-- subtract()

which all as parameters have two Shape objects and the methods combine these two objects
into a single Shape object. The OperationProgram shows how to apply this operation and
opens the following window:

42
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX:
WITH 14: DEVELOPMENT
SOFTWAREOF APPLICATIONS
DEVELOPMENT 2D Shapes
WITH JAVAFX: SOFTWARE DEVELOPMENT 2d shApes

public void start(Stage primaryStage)


{
Group root = new Group();
root.getChildren().add(shape1());
root.getChildren().add(shape2());
root.getChildren().add(shape3());
Scene scene = new Scene(root, 400, 160);
primaryStage.setTitle("Operations");
primaryStage.setScene(scene);
primaryStage.show();
}

private Shape shape1()


{
Circle circ1 = new Circle(80, 70, 50);
Circle circ2 = new Circle(130, 70, 50);
Shape shape = Shape.union(circ1, circ2);
shape.setFill(Color.RED);
return shape;
}

private Shape shape2()


{
Circle circ1 = new Circle(200, 70, 50);
Circle circ2 = new Circle(250, 70, 50);
Shape shape = Shape.intersect(circ1, circ2);
shape.setFill(Color.GREEN);
return shape;
}

private Shape shape3()


{
Circle circ1 = new Circle(320, 70, 50);
Circle circ2 = new Circle(370, 70, 50);
Shape shape = Shape.subtract(circ1, circ2);
shape.setFill(Color.BLUE);
return shape;
}

43
41
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Text

4 TEXT
Text can be represented by a Text object, and the important thing is that Text inherits Shape
and thus can be used as any other Shape object and enter the scene graph as a node. In reality,
there is not much to explain, but the application TextProgram opens the following window:

44
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Text

ItJAVA
works almost the OF
14: DEVELOPMENT same way you know from Java2D, but other classes are used. The
APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT teXt
completed code is as follows:

It works almost the same way you know from Java2D, but other classes are used. The
completed code is as follows:

package textprogram;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.*;
import javafx.stage.Stage;
import javafx.scene.shape.*;
import javafx.scene.paint.*;
import javafx.scene.text.*;
import javafx.geometry.*;

public class TextProgram extends Application


{
@Override
public void start(Stage primaryStage)
{
Group root = new Group();
Shape shape = text1();
root.getChildren().add(shape);
root.getChildren().add(line(shape));
shape = text2();
root.getChildren().add(shape);
root.getChildren().add(rect(shape));
Scene scene = new Scene(root, 530, 250);
primaryStage.setTitle("Strokes");
primaryStage.setScene(scene);
primaryStage.show();
}

private Text text1()


{
Text text = new Text(20, 50, "Hello JavaFX geometry");
text.setFont(Font.font("Liberation Sherif", FontWeight.NORMAL,
FontPosture.REGULAR, 24));
return text;
}

private Line line(Shape shape)


{
Bounds bounds = shape.getBoundsInLocal();
return new Line(20, 50, 20 + bounds.getWidth(), 50);
}

45
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Text
WITH JAVAFX: SOFTWARE DEVELOPMENT teXt

private Text text2()


{
Text text = new Text("Hello World");
text.setX(20);
text.setY(150);
text.setFont(Font.font("Liberation Sherif", FontWeight.BOLD,
FontPosture.ITALIC, 72));
text.setFill(Color.RED);
text.setStroke(Color.BLUE);
text.setStrokeWidth(2);
text.setStrokeType(StrokeType.OUTSIDE);
text.setUnderline(true);
return text;
}

private Rectangle rect(Shape shape)


{
Bounds bounds = shape.getBoundsInLocal();
Rectangle rect = new Rectangle(bounds.getMinX(), bounds.getMinY(),
bounds.getWidth(), bounds.getHeight());
rect.setFill(null);
rect.setStroke(Color.BLACK);
rect.setStrokeWidth(1);
rect.setStrokeType(StrokeType.OUTSIDE);
return rect;
}

public static void main(String[] args)


{
launch(args);
}
}

The top
The top text
text is
is created
created by
by the
the method
method text1()
text1() as
as aa Text
Text object.
object. Here
Here you
you should
should note
note that
that the
the
constructor as
constructor as parameters
parameters has
has the
the coordinates
coordinates ofof the
the text
text and
and that
that the
the coordinates
coordinates indicate
indicate
the left
the left end
end ofof the
the baseline
baseline (the
(the line
line on
on which
which thethe text
text is
is “on”).
“on”). Otherwise,
Otherwise, you
you should
should
especially note
especially note howhow to
to create
create aa font.
font. This
This happens
happens with
with aa static
static method
method font()
font() in
in the
the class
class
Font as
Font as well
well as
as two
two enumerations
enumerations FontWeight
FontWeight and
and FontPosture.
FontPosture.

The method
The method line()
line() has
has aa Shape
Shape object
object as
as parameter,
parameter, and
and thethe method
method creates
creates aa Line
Line object
object
that corresponds
that corresponds toto the
the baseline
baseline of
of the
the text
text created
created in
in text1().
text1(). Here
Here you you should
should especially
especially
note the
note the method
method getBoundsInLocal(),
getBoundsInLocal(), which
which returns
returns aa Bounds
Bounds object
object (defined
(defined inin the
the package
package
javafx.geometry) that
javafx.geometry) that contains
contains the
the Shape
Shape object
object width
width and
and height
height as
as well
well as
as its
its location,
location, and
and
thus the
thus the circumscribing
circumscribing rectangle.
rectangle. Regarding
Regarding the
the latter,
latter, itit is
is not
not aa (x,
(x, y)
y) value,
value, but
but instead
instead
the smallest
the smallest and
and largest
largest xx and
and yy value
value that
that may
may occur,
occur, respectively.
respectively.

46
44
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Text

The method getBoundsInLocal() returns the circumscribing rectangle before any transformation.
There is also a method getBoundsInParent() that returns the circumscribing rectangle after
a transformation. In this case, Bounds uses alone the object to determine the length of the
line to be drawn.

The method text2() creates a Text object for the lower text. Since a Text object is also a Shape
object, you can indicate both fill and stroke just like other shape objects. In this case, the
location of the object is not defined by the constructor, but it is only to show that there
are other options. In particular, note how to indicate that the text needs to be underlined.

Finally, there is method rect() that returns the circumscribing rectangle for the last text, and
here you should primarily note how the rectangle is defined using a Bound object.

47
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Effects

5 EFFECTS
A JavaFX program, as mentioned, represents the content of the user interface as nodes in a
scene graph. It is possible to change how the individual nodes are displayed using so-called
effects, where an effect is an object that is used to modify how a node is to be drawn. It is
primarily interesting for nodes, which represent graphic objects like images and geometric
figures. This chapter is a brief introduction to these effects. Basically, the following effects
are represented as classes in the package javafx.scene.effect :

-- ColorAdjust, which can be used to modify the color of an image where you can
adjust the hue, saturation, brightness and contrast.
-- ColorInput, which corresponds to drawing a rectangle, filled with a color.
-- ImageInput used to fill a rectangular area with an image.
-- Blend, which is used to combine pixels from two inputs.
-- Bloom, which is used to provide a portion of a node more hue.
-- Glow, which is used to increase the hue of a node.
-- BoxBlur, used to perform a blur operation on a node with a box filter.
-- GausienBlur, also used to perform a blur of a node, but instead using a kernel.
-- MotionBlur, which is a gaussien blur, where there is also an angle.
-- Reflection that performs a reflection of a node.
-- SepiaTone, which tones a node with a brownish color.
-- Shadow, resulting in a shadow effect by a blur of edges.
-- DropShadow, where the shadow effect is created behind the node.
-- InnerShadow, where the shadow effect is created within the edge of the node.
-- Lighting, which is used to simulate a light effect, where you can indicate a light
source such as point, distance or sport.
-- Light.Distant, which is a variant of Lighting.
-- Light.Spot, which is a variation of Lighting.
-- Point.Spot, which is a variation of Lighting.

As an example I show a program that adjusts the colors of an image. The program is named
ColorAdjustProgram and opens the following window:

48
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Effects
effeCts

where
where the
the left
left image
image isis the
the original,
original, while
while the
the right
right isis the
the adjusted
adjusted image.
image. The
The program
program
should
should show
show only
only the
the syntax
syntax for
for using
using aa ColorAdjust,
ColorAdjust, butbut in in this
this case
case does
does not
not result
result in
in any
any
improvement
improvement of of the
the image.
image. The
The program
program also
also shows
shows howhow to to load
load aa picture
picture from
from the
the local
local
disk
disk into
into aa JavaFX
JavaFX program.
program. The The program
program code
code isis as
as follows:
follows:

package coloradjustprogram;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.*;
import javafx.stage.Stage;
import javafx.scene.effect.*;
import javafx.scene.image.*;

public class ColorAdjustProgram extends Application


{
@Override
public void start(Stage primaryStage)
{
String filename =
"file:" + System.getProperty("user.home") + "/data/dollar.jpg";
Image image = new Image(filename);
Group root = new Group();
root.getChildren().add(image1(image));
root.getChildren().add(image2(image));
Scene scene = new Scene(root, 460, 250);
primaryStage.setTitle("ColorAdjust");
primaryStage.setScene(scene);
primaryStage.show();
}

49
47
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH14: DEVELOPMENT
JAVAFX: OF DEVELOPMENT
SOFTWARE APPLICATIONS Effects
WITH JAVAFX: SOFTWARE DEVELOPMENT effeCts

private ImageView image1(Image img)


{
ImageView view = new ImageView(img);
view.setX(20);
view.setY(20);
view.setFitWidth(200);
view.setPreserveRatio(true);
return view;
}

private ImageView image2(Image img)


{
ImageView view = new ImageView(img);
view.setX(240);
view.setY(20);
view.setFitWidth(200);
view.setPreserveRatio(true);
ColorAdjust colorAdjust = new ColorAdjust();
colorAdjust.setContrast(0.5);
colorAdjust.setHue(0.5);
colorAdjust.setBrightness(-0.5);

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

50
48
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Effects
WITH JAVAFX: SOFTWARE DEVELOPMENT effeCts

colorAdjust.setSaturation(0.5);
view.setEffect(colorAdjust);
return view;
}

public static void main(String[] args)


{
launch(args);
}
}

The image is loaded in the method start() and is usually done by defining a path to the
The image is loaded in the method start() and is usually done by defining a path to the
image, which is a jpg image. In this case, the image is placed in a directory data under my
image, which is a jpg image. In this case, the image is placed in a directory data under my
home directory, but the image is also part of the book’s zip file with examples. The only
home directory, but the image is also part of the book’s zip file with examples. The only
difference with regard to the file name is that it starts with the name of the protocol as the
difference with regard to the file name is that it starts with the name of the protocol as the
image is located in the local file system. In other cases, it would be the http protocol. The
image is located in the local file system. In other cases, it would be the http protocol. The
image is loaded by creating an Image object.
image is loaded by creating an Image object.

An image is inserted into the program’s scene graph as an ImageView object, and the method
An image is inserted into the program’s scene graph as an ImageView object, and the method
image1() creates an ImageView object for the original image and specifies the coordinates
image1() creates an ImageView object for the original image and specifies the coordinates
of the image’s upper left corner. In addition, you specify the width of the image, and that
of the image’s upper left corner. In addition, you specify the width of the image, and that
its propositions can not be changed.
its propositions can not be changed.

The method image2() correspondingly creates another ImageView object for the same image,
The method image2() correspondingly creates another ImageView object for the same image,
but this time with other coordinates. In addition, a ColorAdjust object is created that has
but this time with other coordinates. In addition, a ColorAdjust object is created that has
methods for adjusting lightness, contrast, saturation and tint. The parameters have values
methods for adjusting lightness, contrast, saturation and tint. The parameters have values
between -1 and 1, where a negative value means reducing the property while a positive
between -1 and 1, where a negative value means reducing the property while a positive
value means increasing the property.
value means increasing the property.

51
49
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Effects

PROBLEM 1

Write a program that opens the window above. The goal is that you can experiment with
the four properties: Light, contrast, hue and saturation. The picture is called stone.jpg and
is contained in the book’s zip file. You must be able to adjust the four properties using the
Slider controls at the top of the window. This means that you should handle the event that
is firing when moving the slider. This happens with a ChangedListener, which is defined in
the javafx.beans.value package.

5.1 COLORS
In the above examples (and also the exercises from the previous chapters) I have used colors
and shown how to fill a shape with a color and draw the perimeter. Generally there are
four options:

1. a uniform color and then objects of the class Color


2. a linear gradiant paint and then objects of the class LinearGradian
3. a radial gradiant paint and then objects of the class RadialGradiant
4. an image and then objects of the class ImagePattern

52
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Effects
effeCts

The
The program
program ColorProgram
ColorProgram opens
opens the
the following
following window:
window:

The
Theprogram’s
program’sscene
scenegraph
graphhas
has88nodes,
nodes,which
whichare
are44Text
Textnodes
nodesand
and44Circle
Circlenodes,
nodes,respectively.
respectively.
AA text
text node
node isis created
created using
using the
the following
following method:
method:

private Text text(String txt, double x, double y, Paint fill, Paint stroke)
{
Text text = new Text(txt);
text.setFont(
Font.font("Liberation Sherif", FontWeight.BOLD, FontPosture.REGULAR, 72));
text.setFill(fill);
text.setStroke(stroke);
text.setStrokeWidth(1);
text.setX(x – text.getBoundsInParent().getWidth() / 2);
text.setY(y + text.getBoundsInParent().getHeight() / 2);
return text;
}

53
51
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Effects
effeCts

The
The parameters
parameters are
are the
the text,
text, the
the coordinates
coordinates ofof the
the shape’s
shape’s position
position and
and the
the colors
colors to
to fill
fill
the
the figure
figure and
and draw
draw the
the perimeter
perimeter respectively.
respectively. You
You should
should note
note that
that aa color
color may
may be
be one
one ofof
the
the above
above four
four options,
options, each
each of
of which
which has
has the
the type
type Paint
Paint as
as the
the base
base type.
type.

AA circle
circle isis created
created using
using the
the following
following method:
method:

private Circle circle(double x, double y, Paint fill, Paint stroke)


{
Circle circ = new Circle(x, y, 100, fill);
if (stroke != null)
{
circ.setStroke(stroke);
circ.setStrokeWidth(1);
}
return circ;
}

Here the
Here the parameters
parameters means
means the
the same
same as
as for
for aa text
text node.
node.

The window
The window shows shows four
four figures,
figures, each
each character
character consisting
consisting of of aa Text
Text node
node and
and aa Circle
Circle node.
node.
The first
The first isis drawn
drawn using
using uniform
uniform colors,
colors, where
where there
there isis nothing
nothing to to say
say in
in relation
relation to
to what
what

54
52
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Effects
effeCts

has
has already
already been
been said
said about
about colors.
colors. The
The next
next figure
figure uses
uses aa linear
linear gradient
gradient paint,
paint, which
which is
is
defined
defined as
as follows:
follows:

private Paint createLinear()


{
Stop[] stops = new Stop[] { new Stop(0, Color.BLUE), new Stop(1, Color.RED)};
return new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, stops);
}

A linear
A linear gradient
gradient paint
paint is
is defined
defined by
by two
two or
or more
more colors,
colors, which
which areare defined
defined as
as objects
objects of
of the
the
type Stop.
type Stop. Each
Each stop
stop indicates
indicates aa color
color and
and aa position
position that
that can
can either
either be
be relative
relative or
or absolute.
absolute.
The first
The first color
color stop
stop is
is in
in this
this case
case blue
blue and
and the
the position
position is
is 0,
0, which
which means
means that
that the
the color
color
is the
is the start
start color.
color. The
The other
other color
color is
is red
red and
and the
the position
position is
is 1,
1, which
which means
means that
that the
the last
last
color value
color value must
must bebe red.
red. All
All colors
colors between
between these
these two
two extremes
extremes areare blends
blends of
of blue
blue and
and red.
red.

The LinearGradient
The LinearGradient parameters
parameters areare the
the starting
starting position
position (here
(here (0.0))
(0.0)) and
and the
the final
final position
position
(here (1.0)),
(here (1.0)), and
and the
the next
next parameter
parameter indicates
indicates that
that the
the coordinates
coordinates must
must bebe interpreted
interpreted
relative (true)
relative (true) or
or absolute.
absolute. In
In this
this case,
case, the
the coordinates
coordinates indicate
indicate that
that they
they must
must bebe mixed
mixed
along the
along the xx axis
axis from
from the
the left
left edge
edge ofof the
the shape
shape to
to the
the right
right edge
edge ofof the
the shape.
shape. The
The next
next
last parameter
last parameter indicates
indicates whether
whether the the pattern
pattern should
should be
be repeated
repeated ifif the
the coordinates
coordinates dodo not
not
define the
define the entire
entire shape,
shape, and
and finally
finally the
the last
last parameter
parameter isis the
the color
color stops.
stops.

A radial
A radial gradient
gradient paint
paint is
is defined
defined in
in almost
almost the
the same
same way:
way:

private Paint createRadial()


{
Stop[] stops = new Stop[]
{ new Stop(0, Color.WHITE), new Stop(0.2, Color.
RED), new Stop(1, Color.BLUE) };
return new RadialGradient(0, 0, 0.6, 0.5, 1, true, CycleMethod.NO_CYCLE, stops);
}

Again, two or more color stops must be defined, and in this case three are defined. They
Again, two or more color stops must be defined, and in this case three are defined. They
say that starting with a white color, and after 20% the color should be red for the last to
say that starting with a white color, and after 20% the color should be red for the last to
be blue. Parameters for a RadialGradient begins by defining a starting point, which is the
be blue. Parameters for a RadialGradient begins by defining a starting point, which is the
focus point and is the first stop. The first parameter is the angle of this focus point, while
focus point and is the first stop. The first parameter is the angle of this focus point, while
the next is the distance to the focus point. The next two parameters are the coordinates of
the next is the distance to the focus point. The next two parameters are the coordinates of
the focus point, while the next is the radius of a circle that defines the area that the Paint
the focus point, while the next is the radius of a circle that defines the area that the Paint
object is about. The last three parameters means the same as for a LinearGradient.
object is about. The last three parameters means the same as for a LinearGradient.

55
53
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Effects
effeCts

Finally,
Finally, there
there isis an
an ImagePattern,
ImagePattern, which
which isis aa Paint
Paint object
object that
that draws
draws an
an image.
image. In
In the
the program’s
program’s
start()
start() method
method an an image
image (Bean.png)
(Bean.png) isis loaded
loaded as
as an
an Image
Image object.
object. This
This image
image cancan then
then be
be
used
used to
to create
create an an ImagePattern
ImagePattern object:
object:

private Paint createImage()


{
return new ImagePattern(image, 0, 0, 48, 48, false);
}

In
In addition
addition to
to the
the image,
image, the
the parameters
parameters are are the
the starting
starting coordinate
coordinate of of the
the figure
figure (upper
(upper left
left
corner),
corner), the
the width
width andand height
height ofof the
the figure
figure (the
(the figure
figure isis scaled
scaled to
to this
this size),
size), and
and whether
whether
the
the coordinates
coordinates should
should be
be interpreted
interpreted relative
relative or
or absolute.
absolute.

5.2 IMAGES
5.2 IMAGES
In
In the
the previous
previous examples,
examples, II have
have already
already shown
shown howhow to
to load
load an
an image
image andand display
display itit in
in
aa window.
window. Actually,
Actually, pictures
pictures do
do not
not have
have much
much to to do
do with
with effects,
effects, but
but some
some are
are pictures
pictures
used
used in
in the
the example
example above,
above, and
and there
there are
are aa few
few more
more remarks
remarks toto add,
add, so
so therefore
therefore aa few
few
additional
additional examples.
examples.

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

56
54
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Effects
effeCts

An
An image
image isis displayed
displayed in
in aa scene
scene graph
graph as as an
an ImageView
ImageView node,
node, and
and the
the image
image itself
itself isis
represented
represented inin the
the program
program asas an
an Image
Image object
object andand can
can be
be loaded
loaded from
from the
the machine’s
machine’s hard
hard
disk
disk by
by specifying
specifying the
the path
path of
of the
the image
image as
as aa parameter
parameter to to the
the constructor.
constructor. The
The following
following
program
program isis called
called ImageViewProgram
ImageViewProgram and and itit opens
opens the
the following
following window:
window:

ItIt isis the


the same
same image
image shown
shown three
three times,
times, and
and the
the example
example should
should primarily
primarily show
show how
how toto
scale
scale an an image.
image. TheThe first
first image
image (the
(the big
big one)
one) isis unscaled
unscaled while
while the
the two
two others
others are
are scaled.
scaled.
The
The code code isis as
as follows:
follows:

package imageviewerprogram;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.*;
import javafx.scene.effect.*;
import javafx.stage.Stage;
import javafx.scene.paint.*;
import javafx.scene.image.*;

public class ImageViewerProgram extends Application


{
private Image image;

public ImageViewerProgram()
{

57
55
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Effects
WITH JAVAFX: SOFTWARE DEVELOPMENT effeCts

String filename =
"file:" + System.getProperty("user.home") + "/data/dollar.jpg";
image = new Image(filename);
}

@Override
public void start(Stage primaryStage)
{
Group root = new Group();
root.getChildren().add(createView(20, 20, 0, 0, true));
root.getChildren().add(createView(440, 20, 100, 200, true));
root.getChildren().add(createView(440, 200, 100, 200, false));
Scene scene = new Scene(root, 560, 440);
primaryStage.setTitle("Colors");
primaryStage.setScene(scene);
primaryStage.show();
}

private ImageView createView(double x, double y, double width, double height,


boolean preserve)
{
ImageView view = new ImageView(image);
view.setX(x);
view.setY(y);
if (width > 0 && height > 0)
{
view.setFitHeight(height);
view.setFitWidth(width);
}
view.setEffect(new DropShadow(5, Color.BLACK));
view.setPreserveRatio(preserve);
return view;
}

public static void main(String[] args)


{
launch(args);
}
}

The image
The image is
is loaded
loaded inin the
the class’
class’ constructor
constructor and
and can
can then
then bebe referred
referred to
to with
with the
the instance
instance
variable image.
variable image. The
The method
method createView()
createView() creates
creates an
an ImageView
ImageView forfor the
the image,
image, and
and it
it has
has five
five
parameters, the
parameters, the first
first two
two being
being the
the coordinates
coordinates ofof the
the ImageView
ImageView object’s
object’s upper
upper left
left corner,
corner,
while the
while the two
two next
next indicate
indicate the
the width
width and
and height.
height. The
The last
last indicates
indicates whether
whether the
the image’s
image’s
propositions are
propositions are to
to be
be retained.
retained. The
The statements
statements ofof the
the method
method areare easy
easy to
to interpret,
interpret, perhaps
perhaps
apart from
apart from the
the meaning
meaning of of setEffect(),
setEffect(), but
but the
the result
result is
is that
that aa frame
frame isis drawn
drawn outside
outside the
the

58
56
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Effects

image. If no width or height is specified, these attributes are not set, and the result is that
the physical dimensions of the image are applied.

Examining the method start() shows that there is no size for the first image. The image
size therefore becomes the physical size, which is 400 × 400. For the next image, the
size is set to 100 × 200, and it will be scaled within this frame, but as it is said that the
propositions are to be saved, the result is an image that is scaled to 1/4 in both directions
and you gets a picture that is 100 × 100. For the last image, the same size is specified, but
the propositions are not preserved, and the image is therefore scaled in both directions, so
it will fill 100 × 200.

As the last example concerning images, I will show a program called PixelProgram. The
program should show how to manipulate the individual pixels in an image. The starting
point is the same picture as shown above. Here is a portion of the image’s pixels white (the
background), and the program should change the background to black. That is, all white
pixels must be changed to black. In general, it is simple, but as it is a jpg image, pixels
close to the figure will not be completely white, and it is therefore necessary to allow an
uncertainty as to when a pixel is white. Performing the program gives you the result:

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

59
JAVA
JAVA14:
14:DEVELOPMENT
DEVELOPMENTOF
OFAPPLICATIONS
APPLICATIONS
WITH
WITHJAVAFX:
JAVAFX:SOFTWARE
SOFTWAREDEVELOPMENT
DEVELOPMENT Effects
effeCts

package pixelsprogram;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.*;
import javafx.scene.effect.*;
import javafx.stage.Stage;
import javafx.scene.paint.*;
import javafx.scene.image.*;

public class PixelsProgram extends Application


{
private Image image;

public PixelsProgram()
{
String filename =
"file:" + System.getProperty("user.home") + "/data/dollar.jpg";
image = new Image(filename);
}

@Override
public void start(Stage primaryStage)
{
Group root = new Group();
root.getChildren().add(createImage());
Scene scene = new Scene(root, 440, 440);
primaryStage.setTitle("Pixels");
primaryStage.setScene(scene);
primaryStage.show();
}

60
58
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Effects
WITH JAVAFX: SOFTWARE DEVELOPMENT effeCts

private ImageView createImage()


{
int width = (int)image.getWidth();
int height = (int)image.getHeight();
WritableImage buffer = new WritableImage(width, height);
PixelReader reader = image.getPixelReader();
PixelWriter writer = buffer.getPixelWriter();
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
{
Color color = reader.getColor(x, y);
if (isWhite(color)) color = Color.BLACK;
writer.setColor(x, y, color);
}
ImageView view = new ImageView(buffer);
view.setX(20);
view.setY(20);
return view;
}

private boolean isWhite(Color color)


{
double epsilon = 0.1;
return 1 – color.getRed() < epsilon && 1 – color.getGreen() < epsilon &&
1 – color.getBlue() < epsilon;
}

public static void main(String[] args)


{
launch(args);
}
}

Most importantly, of course, is the method createImage(), which returns an ImageView


with the modified image. First, the width and height of the image are determined, and a
memory representation of a picture of the same size is created. The type is WritableImage
and I have called it buffer. Next, a PixelReader is defined for the original image, which
means that you can refer to the individual pixels in the image. In addition, a PixelWriter is
created for buffer that allows you to modify the buffer’s pixels. Next, the program iterates
using the reader over the pixels of the original image (line by line), and for each pixel, the
corresponding pixel is updated in buffer – either modified or unchanged. Here you should
note the method isWhite() which tests whether a pixel can be considered white.

61
59
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Effects

5.3 LIGHT
In the introduction to this chapter on effects, I have listed the different effects that you can
apply, and I have far from illustrating them all (and will not), but I want to conclude this
chapter with a little about the effect light. The principle is that a light source shines on a
figure, and the color of the figure is determined by the nature of the light source and its
position in relation to the figure.

Generally, you can associate a lighting effect to a figure with a Lighting object, and if you
do not indicate a light source, a default light source is used, which corresponds to the light
falling directly into the figure, resulting in a weak 3D effect towards the edge. You can also
explicitly indicate a light source, where there are three options:

1. Light.Distant
2. Light.Point
3. Ligth.Spot

62
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Effects

The first corresponds to the light source located at a distance, thus sending light that extends
in one direction from a remote light source:

You can set as a parameter two values (both of the type double):

1. azimuth, which indicates the angle of the light source’s rotation about the z axis
2. elevation, which indicates the angle of the light source’s rotation about the x axis

In addition, you can indicate the color of the light source.

The second option is a light source where the light is sent from a certain point, as indicated
by 3 coordinates. The light spreads in all directions, and in the same way as a Distant light
source, you can indicate the color of the light source.

The light intensity depends on the distance of the source to the figure. Finally, there is the
third option that is similar to the above, but with the difference that you can specify a
specular that controls the focus of the light source.

63
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Effects
effeCts

IfIf you
you run
run the
the application
application LightingProgram,
LightingProgram, itit opens
opens the
the following
following window:
window:

The
The example
example looks
looks like
like ColorProgram,
ColorProgram, but but instead
instead ofof illustrating
illustrating the
the effect
effect ofof colors,
colors, the
the
program
program shows
shows thethe effect
effect of
of light.
light. The
The figures
figures in
in the
the top
top row
row show
show thethe effect
effect of
of aa standard
standard
and
and a distant light source, respectively, while the two figures in the bottom row show the
a distant light source, respectively, while the two figures in the bottom row show the
effect
effect of
of aa spot
spot and
and aa point
point light
light source,
source, respectively.
respectively. The
The code
code of
of the
the program
program is: is:

package lightingprogram;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.*;
import javafx.stage.Stage;
import javafx.scene.effect.*;
import javafx.scene.shape.*;
import javafx.scene.paint.*;
import javafx.scene.text.*;

public class LightingProgram extends Application


{
@Override

64
62
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH14: DEVELOPMENT
JAVAFX: OF DEVELOPMENT
SOFTWARE APPLICATIONS Effects
WITH JAVAFX: SOFTWARE DEVELOPMENT effeCts

public void start(Stage primaryStage)


{
Group root = new Group();
root.getChildren().add(text(140, 50, Color.rgb(232, 232, 232),
new Lighting()));
root.getChildren().add(circle(140, 220, Color.DARKRED, new Lighting()));
root.getChildren().add(text(400, 50, Color.GREEN,
new Lighting(new Light.Distant(45, 60, Color.WHITE))));
root.getChildren().add(circle(400, 220, Color.GREEN,
new Lighting(new Light.Distant(45, 60, Color.WHITE))));
root.getChildren().add(text(140, 370, Color.BLUE,
new Lighting(new Light.Spot(120, 120, 50, 2, Color.WHITE))));
root.getChildren().add(circle(140, 540, Color.BLUE,
new Lighting(new Light.Spot(120, 120, 50, 2, Color.WHITE))));
root.getChildren().add(text(400, 370, Color.RED,
new Lighting(new Light.Point(120, 120, 50, Color.WHITE))));
root.getChildren().add(circle(400, 540, Color.RED,
new Lighting(new Light.Point(120, 120, 50, Color.WHITE))));
Scene scene = new Scene(root, 550, 670);
primaryStage.setTitle("Lighting");
primaryStage.setScene(scene);
primaryStage.show();
}

65
63
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Effects
WITH JAVAFX: SOFTWARE DEVELOPMENT effeCts

private Text text(double x, double y, Paint fill, Lighting light)


{
Text text = new Text("Light");
text.setFont(Font.font("Liberation Sherif", FontWeight.BOLD,
FontPosture.REGULAR, 72));
text.setFill(fill);
text.setStroke(Color.BLACK);
text.setStrokeWidth(1);
text.setX(x – text.getBoundsInParent().getWidth() / 2);
text.setY(y + text.getBoundsInParent().getHeight() / 2);
text.setEffect(light);
return text;
}

private Circle circle(double x, double y, Paint fill, Lighting light)


{
Circle circ = new Circle(x, y, 100, fill);
circ.setEffect(light);
return circ;
}

public static void main(String[] args)


{
launch(args);
}
}

The two methods text() and circle() are similar to the corresponding methods from earlier.
The two methods text() and circle() are similar to the corresponding methods from earlier.
You should primarily consider the method start() and here how to create light sources as
You should primarily consider the method start() and here how to create light sources as
Light objects used as parameters for a Lighting object that is an effect. Note that the specific
Light objects used as parameters for a Lighting object that is an effect. Note that the specific
Light classes are defined as inner classes in the class Light.
Light classes are defined as inner classes in the class Light.

PROBLEM 2
PROBLEM 2
To experiment a little with light sources, write an application that opens the following
To experiment a little with light sources, write an application that opens the following
window:
window:

66
64
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Effects
effeCts

The
The four
four circles
circles mentioned
mentioned from
from the
the left
left are
are using
using the
the light
light sources:
sources:

1.
1. default
default
2.
2. distant
distant
3.
3. spot
spot
4.
4. point
point

The
The setting
setting options
options are
are made
made with
with Slider
Slider controls
controls and
and ComboBox
ComboBox controls,
controls, and
and the
the names
names
should
should explain
explain the
the meaning.
meaning. A A setting
setting option
option does
does not
not necessarily
necessarily have
have effect
effect for
for all
all light
light
sources,
sources, but
but changes
changes aa setting,
setting, the
the change
change must
must bebe reflected
reflected in
in the
the relevant
relevant shapes.
shapes. As
As for
for
ComboBox
ComboBox controls,
controls, they
they must
must be
be initialized
initialized with
with colors
colors and
and II have
have enclosed
enclosed aa color
color in
in the
the
following
following wrapper
wrapper class:
class:

class ColorWrapper
{
private Color color;
private String name;

public ColorWrapper(Color color, String name)


{
this.color = color;
this.name = name;
}

67
65
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Effects
WITH JAVAFX: SOFTWARE DEVELOPMENT effeCts

public Color getColor()


{
return color;
}

public String getName()


{
return name;
}

@Override
public String toString()
{
return String.format("%s [%s]", name, color.toString());
}
}

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

68
66
JAVA
JAVA14:
14:DEVELOPMENT
DEVELOPMENTOF
OFAPPLICATIONS
APPLICATIONS
WITH
WITHJAVAFX:
JAVAFX:SOFTWARE
SOFTWAREDEVELOPMENT
DEVELOPMENT Effects
effeCts

You
You can
can initialize
initialize the
the two
two ComboBox
ComboBox controls
controls with
with anan appropriate
appropriate number
number of of standard
standard
colors
colors (static
(static objects
objects in
in the
the class
class Color),
Color), but
but you
you can
can actually
actually decide
decide all
all of
of them
them using
using the
the
following
following method:
method:

private java.util.List<ColorWrapper> getColors()


{
java.util.List<ColorWrapper> list = new java.util.ArrayList();
try
{
java.lang.reflect.Field[] fields = Color.class.getDeclaredFields();
for (java.lang.reflect.Field field : fields)
{
if (java.lang.reflect.Modifier.isStatic(field.getModifiers()) &&
field.getType().equals(Color.class))
{
Object obj = new Object();
obj = field.get(obj);
list.add(new ColorWrapper((Color)obj, field.getName()));
}
}
}
catch (Exception ex)
{
list.clear();
}
return list;
}

69
67
JAVA 14:
JAVA 14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH JAVAFX:
WITH JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT trAnsformAtIons
Transformations

6 TRANSFORMATIONS
6 TRANSFORMATIONS
JavaFX also
JavaFX also supports
supports transformations
transformations ofof nodes
nodes in
in the
the scene
scene graph,
graph, and
and itit happens
happens largely
largely
in the
in the same
same way
way that
that you
you know
know itit from
from Java2D.
Java2D. Generally,
Generally, there
there are
are 44 transfomations
transfomations

1. Translater
1. Translater
2. Scaling
2. Scaling
3. Rotation
3. Rotation
4. Shearing
4. Shearing

and the
and the meaning
meaning isis the
the same
same asas in
in Java2D.
Java2D. As
As aa simple
simple example,
example, the
the following
following program
program
performs aa translation
performs translation of
of aa rectangle:
rectangle:

package translateprogram;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.stage.Stage;
import javafx.scene.shape.*;
import javafx.scene.paint.Color;
import javafx.scene.transform.*;

public class TranslateProgram extends Application


{
@Override
public void start(Stage stage)
{
Group root = new Group();
root.getChildren().add(createRect(Color.BLUE, null));
root.getChildren().add(createRect(Color.RED, new Translate(50, 50)));
Scene scene = new Scene(root, 350, 200);
stage.setTitle("Rectangles");
stage.setScene(scene);
stage.show();
}

private Rectangle createRect(Color color, Translate trans)


{
Rectangle rect = new Rectangle(20, 20, 200, 100);
rect.setFill(color);
if (trans != null) rect.getTransforms().add(trans);
return rect;
}

68
70
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH 14: DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Transformations
WITH JAVAFX: SOFTWARE DEVELOPMENT trAnsformAtIons

public static void main(String[] args)


{
launch(args);
}
}

The method createRect() creates a Rectangle with a fixed position and size, as well as a parameter
The method createRect() creates a Rectangle with a fixed position and size, as well as a parameter
that is the color. Finally, there is a parameter that can indicate a transformation and thus
that is the color. Finally, there is a parameter that can indicate a transformation and thus
a shift of the rectangle to another position. That is, the program creates two rectangles of
a shift of the rectangle to another position. That is, the program creates two rectangles of
the same size and position, but one (the red) translated 50 pxels in both directions:
the same size and position, but one (the red) translated 50 pxels in both directions:

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

71
69
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Transformations

EXERCISE 16
Write a program that opens the following window:

The blue rectangle has the top corner in (20, 20) while the size is 200 × 100. The red
rectangle is a scaling of the blue where it is scaled to 50% in both directions and from the
point (20, 20). The green rectangle is a corresponding scale, but followed by a translation.
Note that in the case of compound transformations, the order means something.

EXERCISE 17
Write an application that opens the window below. Here the blue rectangle has the upper
left corner in (180, 180) while the size is 200 × 100. The red rectangle is a rotation of 45
degrees of the blue rectangle about the point (180, 180). The green rectangle is a rotation
about the same point, but with the angle -45 degrees, and the rotation is followed by
a translation.

72
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Transformations

EXERCISE 18
Write a program that opens a window similar to the following when the red rectangle is to
be a shearing of the blue rectangle:

6.1 ANIMATIONS
In this section I introduce animations, which you also can perceive as a form of transformations
of a node. An animation basically means changing one or the properties of a node, and if
you do it many times and do it at short intervals, it will seem to the user as if something
is “alive” with that node. As described in Java 10, a node needs to be redrawn at short
intervals, and such that the value of an option has been changed for each redraw. In JavaFX,
this logic is encapsulated in a number of classes, where each class defines an animation
for a particular value or property. The base class is called a Transition, but there are the
following specific transitions:

-- FadeTransition
-- FillTransition
-- RotateTransition
-- ScaleTransition
-- StrokeTransition
-- TranslateTransition
-- PathTransition
-- SequentialTransition
-- PauseTransition
-- ParallelTransition

73
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Transformations

and the names tells a little about what it is for properties that the class in question is an
animation for. As an example, I will show you how to use a FadeTransition. A visual node
has an opacity property that indicates the extent to which that node should be displayed
transparent. If you perform an animation of this property, you can see that the figure appears
fully drawn, after which it appears more transparent until it completely disappears. It is
the task of a FadeTransition. If you run the program FadeAnimation, the following window
shows a red circle:

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

74
JAVA
JAVA 14:
14: DEVELOPMENT APPLICATIONS
DEVELOPMENT OF APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE DEVELOPMENT
SOFTWARE DEVELOPMENT Transformations
trAnsformAtIons

The circle
The circle becomes weaker and weaker
weaker and
and finally
finallydisappears
disappearscompletely.
completely.Then
Thenititgrows
growsagain
again
until itit is
until is shown as it original was.
was. This
This cycle
cycle isis repeated
repeated 55 times.
times.The
Thecode
codeisisasasfollows:
follows:

package fadeanimation;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.shape.*;
import javafx.scene.paint.Color;
import javafx.animation.*;
import javafx.util.*;

public class FadeAnimation extends Application


{
@Override
public void start(Stage stage)
{
Group root = new Group();
Circle circ = createCircle();
root.getChildren().add(circ);
Transition trans = createTransition(circ);
Scene scene = new Scene(root, 250, 250);
stage.setTitle("Fade");
stage.setScene(scene);
stage.show();
trans.play();
}

private Circle createCircle()


{
return new Circle(120, 120, 100, Color.RED);
}

private FadeTransition createTransition(Node node)


{
FadeTransition trans = new FadeTransition(Duration.millis(2000), node);
trans.setFromValue(1);
trans.setToValue(0);
trans.setCycleCount(10);
trans.setAutoReverse(true);
return trans;
}

public static void main(String[] args)


{
launch(args);
}
}

73
75
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Transformations
trAnsformAtIons

The
The method
method createCircle()
createCircle() isis trivial,
trivial, while
while itit isis the
the method
method createTransition()
createTransition() that
that creates
creates the
the
transition.
transition. InIn this
this case,
case, itit isis aa FadeTransition,
FadeTransition, and and the
the constructor
constructor tells
tells that
that the
the animation
animation
should
should take
take 22 seconds,
seconds, andand what what itit isis for
for aa node
node that
that the
the animation
animation should
should workwork on.
on.
Otherwise, the animation must change the value from from 1 (not
Otherwise, the animation must change the value from from 1 (not transparent) to 0 (total transparent) to 0 (total
transparent).
transparent). The The next
next statement
statement tells tells the
the animation
animation to to be
be repeated
repeated 1010 times
times and
and finally,
finally,
after
after the
the animation
animation isis complete,
complete, the the next
next oneone must
must go
go backwards.
backwards. In In start(),
start(), aa Transition
Transition
object
object isis created
created and
and the
the statement
statement

trans.play();

starts the
starts the animation.
animation.

The other
The other animation
animation classes
classes are
are used
used in
in the
the same
same way,
way, but
but instead
instead ofof showing
showing examples,
examples, II
have formulated
have formulated aa series
series of
of exercises
exercises that
that will
will illustrate
illustrate applications
applications ofof the
the most
most important
important
classes. You
classes. You can
can immediately
immediately start
start from
from the
the above
above program,
program, but
but for
for some
some of
of the
the exercises
exercises
itit isis necessary
necessary to
to read
read the
the documentation
documentation to to find
find out
out what
what toto write
write –– which
which values
values should
should
be initialized.
be initialized.

EXERCISE 19
EXERCISE 19
Write an
Write an application
application that
that opens
opens aa window
window with
with aa blue
blue circle:
circle:

Then the
Then the program
program should
should with
with aa FillTransition
FillTransition change
change color
color to
to red.
red. The
The animation
animation must
must take
take
55 seconds
seconds and
and then
then start
start again
again with
with aa blue
blue circle.
circle. The
The animation
animation must
must be be repeated
repeated 50
50 times.
times.
Note that
Note that aa FillTransition
FillTransition can
can not
not be
be applied
applied to
to aa general
general node,
node, but
but itit must
must be
be aa Shape.
Shape.

76
74
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Transformations

EXERCISE 20
Write a program that you can call ScaleAnimation, which opens a window with a red circle:

The program must, with an animation, change the size of the circle, so it will shrink and grow.

EXERCISE 21
Write a program that you can call TranslateAnimation. The program must open a window,
as shown below, where a red circle with an animation is moved from the upper left corner
to the bottom right corner. You can use a TranslateTransition. The animation period must

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

77
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Transformations

be 2 seconds and the animation must be repeated 50 times. You must also set AutoReverse
to true.

EXERCISE 22
You must write a program called RotateAnimation, which shows a rectangle. The rectangle
should rotate from 0 to 360 degrees, and simultaneously the color must change from red
to blue – and back again in the next rotation:

Note that this time you will need to use two transitions.

78
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Transformations

EXERCISE 23
Write a program PathAnimation, where a red circle moves along a CubicCurve (see below).
The curve must be defined as a Path object, and as a transition object you can use a
PathTransition. An animation of the circle must run for two seconds, and you must set
AutoReverse to true.

EXERCISE 24
As the last example of an animation, write a program SequentialAnimation similar to the
above, where a red circle moves along a CubicCurve, but the animation is only repeated
once. When the circle reaches the end of the curve (the animation stops), the circle should
with an animation change color to blue and back to red again. The program must therefore
use two animations that are performed sequentially.

79
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

7 COMPONENTS
Looking at the foregoing, I have primarily focused on how you in JavaFX works with
geometric objects, but I have only overall mentioned components that the user can interact
with. Viewed from practical programs it is of course the most interesting and is the subject
of this and the following chapters. It is about which components are available and how
they are laid out in a window. In addition, there is event management.

7.1 LAYOUT
The program’s scene graph consists of components, and these components can be placed
absolutely as I have used in conjunction with geometric objects, but typically, nodes are

360°
placed in the scene graph using layout panes where a layout pane is an branch node. Viewed

.
from the programmer, a layout pane has the same characteristics (and purposes) as a layout

thinking
manager in Swing, and the theory resembles what you know from Swing. All layout panes
have a common basic class Pane, and there are the following specific panes:

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


80
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

-- HBox
-- VBox
-- BorderPane
-- StackPane
-- Flow Pane
-- TextFlow
-- AnchorPane
-- TitlePane
-- Grid Pane

In this section I show how the layout panes are used to layout components, and of course
they can be nested in the same way you know it from Swing. The following examples are
similar to each other and briefly show the application of the different panes, but you should
examine the online documentation and what properties are available.

I want to start with a HBox (the HBoxProgram application) which places components
horizontally in a window, and here with three buttons:

As you can see, the size of the buttons (width) changes according to the available space,
and below I have shown the same window after the size has changed:

As you can see, the components are as default left-aligned, but it can be changed with a
property. The code is as follows:

81
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX:
WITH 14: DEVELOPMENT
SOFTWAREOF APPLICATIONS
DEVELOPMENT Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

package hboxprogram;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.stage.*;

public class HBoxProgram extends Application


{
@Override
public void start(Stage stage)
{
HBox root = new HBox();
root.setSpacing(10);
root.getChildren().add(createButton("A button"));
root.getChildren().add(createButton("Another button"));
root.getChildren().add(createButton("A big button", 200, 50));
Scene scene = new Scene(root, 300, 100);
stage.setTitle("HBox");
stage.setScene(scene);
stage.show();
}

private Button createButton(String text)


{
return new Button(text);
}

private Button createButton(String text, int width, int height)


{
Button cmd = new Button(text);
cmd.setPrefSize(width, height);
return cmd;
}

public static void main(String[] args)


{
launch(args);
}
}

You may notice that the last method createButton() assigns the button a preferred size, and
You may notice that the last method createButton() assigns the button a preferred size, and
in JavaFX, basically, the same applies to a component’s size, as you know from Swing. As
in JavaFX, basically, the same applies to a component’s size, as you know from Swing. As
for the method start(), there is not much to explain, but you should note how to define a
for the method start(), there is not much to explain, but you should note how to define a
gap between the components. A HBox is a very simple layout pane and can only be used
gap between the components. A HBox is a very simple layout pane and can only be used
to arrange components on a line relative to their preferred size.
to arrange components on a line relative to their preferred size.

82
80
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components

There
There isis aa layout
layout pane,
pane, called
called VBox,
VBox, which
which isis parallel
parallel to
to HBox,
HBox, the
the difference
difference being
being that
that itit
places
places the
the components
components onon aa vertical
vertical line.
line. The
The VBoxProgram
VBoxProgram program
program shows
shows the
the application
application
of
of this
this layout
layout pane:
pane:

public void start(Stage stage)


{
VBox root = new VBox();
root.setSpacing(10);
root.setAlignment(Pos.CENTER);
root.getChildren().add(createButton("A button"));
root.getChildren().add(createButton("Another button"));
root.getChildren().add(createButton("A big button", 200, 50));

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

83
81
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
JAVA 14:
WITH 14: DEVELOPMENT
JAVAFX: SOFTWARE
DEVELOPMENT OF
OF APPLICATIONS
DEVELOPMENT
APPLICATIONS Components
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components

Scene
Scene scene
scene == new
new Scene(root,
Scene(root, 300,
300, 200);
200);
stage.setTitle("VBox");
stage.setTitle("VBox");
stage.setScene(scene);
stage.setScene(scene);
stage.show();
stage.show();
}}

There is not much new to explain, but you should note how to indicate that the components
should be displayed centered in the window. You are encouraged to investigate what options
the type
the type of
of Pos
Pos otherwise
otherwise defines.
defines.

A BorderPane looks like a BorderLayout and divides the window into 5 areas, called center,
top, right, bottom and left and usually referenced in this order. As with a BorderLayout, the
center will
center will fill
fill what
what has
has not
not been
been used
used by
by the
the other
other areas.
areas. The
The program
program BorderProgram
BorderProgram opens
opens
the window
the window shown
shown below.
below. In
In addition
addition to
to show
show aa BorderPane,
BorderPane, the
the program
program should
should also
also show
show
the use of nested panes. The window has 9 components:

1. center 
1. center:: aa TextArea
TextArea
2. top:
2. top: aa BorderPane
BorderPane with
with aa TextField
TextField and
and aa Button
Button
3. right: a BorderPane with a Button and a TextArea
3.
4. bottom: a BorderPane with a TextField and a Button
4.
5. left 
5. left:: aa BorderPane
BorderPane with
with aa Button
Button and
and aa TextArea
TextArea

You should notice the spacing between the components and how they are defined in the code.

public
public class
class BorderProgram
BorderProgram extends
extends Application
Application
{{
@Override
@Override
public
public void
void start(Stage
start(Stage stage)
stage)
{{
BorderPane
BorderPane root
root ==

84
82
82
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

new BorderPane(createField(), createField("Top"), createField("Right", 100),


createField("Buttom"), createField("Left", 100));
root.setPadding(new Insets(20, 20, 20, 20));
Scene scene = new Scene(root, 500, 300);
stage.setTitle("Border");
stage.setScene(scene);
stage.show();
}

private Pane createField()


{
BorderPane pane = new BorderPane(new TextArea());
pane.setPadding(new Insets(10, 10, 10, 10));
return pane;
}

private Pane createField(String text)


{
Button cmd = new Button(text);
cmd.setPrefWidth(80);
BorderPane pane = new BorderPane(new TextField(), null, cmd, null, null);
BorderPane.setMargin(cmd, new Insets(0, 0, 0, 10));
return pane;
}

private Pane createField(String text, int width)


{
Button cmd = new Button(text);
cmd.setPrefWidth(width);
TextArea field = new TextArea();
field.setPrefWidth(width);
BorderPane pane = new BorderPane(field, cmd, null, null, null);
BorderPane.setMargin(cmd, new Insets(10, 0, 10, 0));
BorderPane.setMargin(field, new Insets(0, 0, 10, 0));
return pane;
}

public static void main(String[] args)


{
launch(args);
}
}

The individual 5 areas are created with three helper methods named createField(). The first is
used for the center and creates a BorderPane with a TextArea component. You should notice
how to set a spacing of 10 to the remaining 4 areas with setPadding(). Also note that the
BorderPane constructor specifies a single parameter, which is the component to be shown

85
83
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components

at
at the
the center.
center. The
The second
second createField()
createField() is
is used
used toto create
create aa BorderPane
BorderPane toto be
be placed
placed at
at top
top
and
and bottom
bottom respectively.
respectively. Here
Here you
you specify
specify 55 parameters
parameters for for the
the constructor
constructor inin BorderPane,
BorderPane,
which
which is interpreted as center, top, right, bottom and left. In particular, note how to
is interpreted as center, top, right, bottom and left. In particular, note how to define
define
that the button should have a left margin in the container:
that the button should have a left margin in the container:

BorderPane.setMargin(cmd, new Insets(0, 0, 0, 10));

Here,
Here, setMargin()
setMargin() is
is aa static
static method
method inin the
the BorderPane
BorderPane class,
class, which
which defines
defines the
the margin
margin ofof
the
the first
first parameter
parameter in
in the
the current
current layout
layout pane.
pane. The
The last
last createField()
createField() method
method is is used
used to
to create
create
aa BorderPane
BorderPane for the contents of the right and left area and, in principle, it works as the
for the contents of the right and left area and, in principle, it works as the
previous method. You should note that a bottom margin is defined for both
previous method. You should note that a bottom margin is defined for both components. components.

Finally,
Finally, there
there is
is the
the start()
start() method,
method, where
where the
the root
root element
element this
this time
time is
is aa BorderPane
BorderPane (which
(which
is
is a branch node). Here you should note how to create root, and to set a margin of 20.
a branch node). Here you should note how to create root, and to set a margin of 20.

A
A StackPane
StackPane is
is aa layout
layout pane
pane that
that arranges
arranges the
the components
components on
on top
top of
of each
each other
other in
in the
the order
order
they
they are
are added.
added. The
The program
program StackProgram
StackProgram shows
shows three
three buttons
buttons placed
placed on
on top
top of
of each
each other:
other:

86
84
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components

The application is probably limited, but primarily for Shape objects, the possibility can be
useful. It’s quite simple to use a StackPane:

public void start(Stage stage)


{
StackPane root = new StackPane();
root.getChildren().add(createButton("A very big button with a big font",
500, 100, 24));
root.getChildren().add(createButton("A big button in the middle", 250, 50, 16));
root.getChildren().add(createButton("A small button", 150, 25, 12));
Scene scene = new Scene(root, 600, 200);
stage.setTitle("Stack");
stage.setScene(scene);
stage.show();
}

private Button createButton(String text, int width, int height, int size)
{
Button cmd = new Button(text);
cmd.setFont(Font.font(size));
cmd.setPrefSize(width, height);
return cmd;
}

A FlowPane is a layout pane that essentially behaves like a FlowLayout in Swing:


A FlowPane is a layout pane that essentially behaves like a FlowLayout in Swing:

85
87
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

IfIf
If you
you increase
you increase the
increase the width
the width of
width of the
of the window,
the window, all
window, all components
all components will
components will appear
will appear on
appear on the
on the same
the same line.
same line.
line.
Regarding
Regarding the
the code,
code, you
you should
should first
first notice
notice how
how to
to define
define the
the gap
gap between
between the
the
Regarding the code, you should first notice how to define the gap between the components: components:
components:

public
public void
void start(Stage
start(Stage stage)
stage)
{
{
FlowPane
FlowPane root
root == new
new FlowPane();
FlowPane();
root.setAlignment(Pos.TOP_LEFT);
root.setAlignment(Pos.TOP_LEFT);
root.setHgap(5);
root.setHgap(5);
root.setVgap(10);
root.setVgap(10);
root.getChildren().add(createButton("Button
root.getChildren().add(createButton("Button A"));
A"));
root.getChildren().add(createButton("Button
root.getChildren().add(createButton("Button B"));
B"));
root.getChildren().add(createButton("Button
root.getChildren().add(createButton("Button C"));
C"));
root.getChildren().add(createButton("Button
root.getChildren().add(createButton("Button D"));
D"));
Scene
Scene scene
scene == new
new Scene(root,
Scene(root, 300,
300, 150);
150);
stage.setTitle("Flow");
stage.setTitle("Flow");
stage.setScene(scene);
stage.setScene(scene);
stage.show();
stage.show();
}
}

There
There isis
There also
also aaa layout
is also layout pane,
layout pane, which
which isis
pane, which called
is called TextFlow,
called TextFlow, and
TextFlow, and behaving
and behaving
behaving in in the
in the same
the same
same way way
way asas
as aaa
FlowPane,
FlowPane, but
FlowPane, but only
but only for
only for Text
for Text nodes.
Text nodes. The
nodes. The program
The program TextflowProgram
program TextflowProgram shows
TextflowProgram shows
shows howhow
how to to
to useuse this
use this
this
pane. It’s
pane. It’s
pane. probably
It’s probably
probably not not the
not the most
the most commonly
most commonly
commonly used used layout
used layout pane,
layout pane, but
pane, but it may
but itit may
may bebe useful
be useful if you
useful ifif you
you
need to
need to
need write
to write a custom
write aa custom component
custom component that
component that supports
that supports text
supports text wrapping
text wrapping – something
wrapping –– something
something that that is actually
that isis actually
actually
relatively complicated
relatively complicated
relatively complicated in in Swing.
in Swing.
Swing.

public
public void
void start(Stage
start(Stage stage)
stage)
{
{
TextFlow
TextFlow root
root == new
new TextFlow();
TextFlow();
root.setLineSpacing(10);
root.setLineSpacing(10);
root.getChildren().add(createText("Gorm
root.getChildren().add(createText("Gorm den
den Gamle,
Gamle, ",
", Color.BLUE));
Color.BLUE));
root.getChildren().add(createText("Harald
root.getChildren().add(createText("Harald Blåtand,
Blåtand, ",
", Color.GREEN));
Color.GREEN));
root.getChildren().add(createText("Svend
root.getChildren().add(createText("Svend Tveskæg",
Tveskæg", Color.RED));
Color.RED));
Scene
Scene scene
scene == new
new Scene(root,
Scene(root, 300,
300, 100);
100);
stage.setTitle("TextFlow");
stage.setTitle("TextFlow");
stage.setScene(scene);
stage.setScene(scene);
stage.show();
stage.show();
}
}

86
88
86
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA JAVAFX:
WITH
WITH 14: DEVELOPMENT
JAVAFX: SOFTWAREOF
SOFTWARE APPLICATIONS
DEVELOPMENT
DEVELOPMENT Components
Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

private Text createText(String text, Color color)


private Text createText(String text, Color color)
{
{
Text node = new Text(text);
Text node = new Text(text);
node.setStroke(color);
node.setStroke(color);
return node;
return node;
}
}

An AnchorPane
An AnchorPane places
places aa component
component relative
relative to
to the
the container’s
container’s edge:
edge:
An AnchorPane places a component relative to the container’s edge:
public void start(Stage stage)
public void start(Stage stage)
{
{
AnchorPane root = new AnchorPane();
AnchorPane root = new AnchorPane();
root.setPadding(new Insets(30, 30, 30, 30));
root.setPadding(new Insets(30, 30, 30, 30));
Button cmd = createButton("A button");
Button cmd = createButton("A button");
root.getChildren().add(cmd);
root.getChildren().add(cmd);
AnchorPane.setRightAnchor(cmd, 30.0);
AnchorPane.setRightAnchor(cmd, 30.0);
AnchorPane.setBottomAnchor(cmd, 50.0);
AnchorPane.setBottomAnchor(cmd, 50.0);
Scene scene = new Scene(root, 300, 200);
Scene scene = new Scene(root, 300, 200);
stage.setTitle("Anchor");
stage.setTitle("Anchor");
stage.setScene(scene);
stage.setScene(scene);
stage.show();
stage.show();
}
}

AXA Global
Graduate Program
Find out more and apply

87
89
87
JAVA 14:
JAVA 14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH JAVAFX:
WITH JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components

In
In this
this case,
case, root
root has
has aa margin
margin of
of 30,
30, and
and the
the component
component isis positioned
positioned soso that
that itit sits
sits 30
30 from
from
the
the right
right edge
edge (relative
(relative to
to the
the margin)
margin) and
and 50
50 above
above the
the bottom
bottom (relative
(relative to
to the
the margin).
margin). If
If
the
the window’s
window’s size
size changes,
changes, the
the component
component will
will follow
follow the
the bottom
bottom and
and right
right edges.
edges.

Then
Then there
there isis aa TilePane,
TilePane, which
which places
places components
components into into cells
cells of
of the
the same
same size.
size. The
The size
size of
of
the
the cells
cells isis determined
determined byby the
the largest
largest preferred
preferred size
size (in
(in this
this case
case the
the last
last button).
button). IsIs there
there
no
no room
room for for all
all components
components onon the
the line,
line, the
the line
line wraps,
wraps, so
so the
the last
last component
component appears
appears on on
the
the next
next line.
line.

public void start(Stage stage)


{
TilePane root = new TilePane();
root.getChildren().add(createButton("A button"));
root.getChildren().add(createButton("Another button"));
root.getChildren().add(createButton("A big button", 200, 50));
Scene scene = new Scene(root, 650, 100);
stage.setTitle("Tile");
stage.setScene(scene);
stage.show();
}

In
In this
this case,
case, the
the components
components areare set
set horizontally,
horizontally, which
which isis default,
default, but
but with
with aa property,
property, itit
isis possible
possible to
to specify
specify that
that the
the components
components should
should be
be laid
laid out
out vertically.
vertically.

Finally,
Finally, there
there isis aa GridPane,
GridPane, which
which isis aa very
very useful
useful layout
layout pane.
pane. Compared
Compared withwith Swing,
Swing, you
you
can achieve a bit of the same as with a GridBagLayout, but it is far easier to use.
can achieve a bit of the same as with a GridBagLayout, but it is far easier to use. Basically, Basically,

88
90
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components

it’s
it’s aa grid.
grid. but
but the
the cells
cells do
do not
not necessarily
necessarily have
have the
the same
same size.
size. The
The program
program GridProgram
GridProgram
opens
opens thethe following
following window:
window:

that has
that has 55 components:
components:

--- 22 Label
Label components
components
--- 22 TextField
TextField components
components
--- 11 Button
Button component
component

IfIf you
you change
change thethe window
window size,
size, the
the components
components willwill stay
stay at
at their
their positions
positions and
and with
with the
the
same size
same size –– at
at least
least as
as long
long as
as the
the window
window isis large
large enough.
enough. ItIt isis therefore
therefore aa typical
typical dialog
dialog
box. The
box. The code
code isis quite
quite simple:
simple:

package gridprogram;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.stage.*;
import javafx.geometry.*;

public class GridProgram extends Application


{
@Override
public void start(Stage stage)
{
GridPane root = new GridPane();
root.setPadding(new Insets(20, 20, 20, 20));
root.setVgap(20);
root.add(createLabel("First name", 80), 0, 0);
root.add(createField(300), 1, 0);
root.add(createLabel("Last name", 80), 0, 1);
root.add(createField(300), 1, 1);

89
91
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH14:JAVAFX:
DEVELOPMENT OF APPLICATIONS
SOFTWARE DEVELOPMENT Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

Button cmd = createButton("OK");


root.add(cmd, 1, 2);
GridPane.setHalignment(cmd, HPos.RIGHT);
Scene scene = new Scene(root, 500, 200);
stage.setTitle("Grid");
stage.setScene(scene);
stage.show();
}

private Label createLabel(String text, int width)


{
Label label = new Label(text);
label.setPrefWidth(width);
return label;
}

private TextField createField(int width)


{
TextField field = new TextField();
field.setPrefWidth(width);
return field;
}

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

92
90
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
JAVA 14:
WITH 14: DEVELOPMENT
DEVELOPMENT
JAVAFX: SOFTWAREOF
OF APPLICATIONS
APPLICATIONS
DEVELOPMENT Components
WITH JAVAFX: SOFTWARE DEVELOPMENT
WITH JAVAFX: SOFTWARE DEVELOPMENT Components
Components

private
private Button
Button createButton(String
createButton(String text)
text)
{{
return
return new
new Button(text);
Button(text);
}}

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

In the
In the method
method start(),
start(), aa GridPane
GridPane is is created
created asas root.
root. Note
Note that
that you
you do do not
not say
say anything
anything
about the
about the number
number of of rows
rows and
and columns.
columns. There
There isis aa margin
margin of of 20,
20, and
and there
there must
must be be aa gap
gap
of 20
of 20 between
between the
the individual
individual rows.
rows. Then
Then II add
add aa Label
Label with
with the
the width
width 80,80, and
and II define
define that
that
it should
it should be
be in
in cell
cell (0,
(0, 0),
0), which
which is is the
the cell
cell in
in the
the upper
upper left
left corner.
corner. The
The next
next component
component
is aa TextField
is TextField with
with the
the width
width 300,
300, which
which should
should be be in
in cell
cell (1,
(1, 0),
0), which
which cancan bebe translated
translated
into column
into column 11 and
and row
row 0. 0. Similarly,
Similarly, thethe two
two next
next components
components are are placed
placed solely
solely with
with thethe
difference that
difference that they
they should
should bebe placed
placed in in row
row 1.1. Finally,
Finally, place
place the
the button
button in in cell
cell (1,
(1, 2)
2) and
and
thus column
thus column 11 row
row 2.2. Note
Note that
that nothing
nothing is is placed
placed in in cell
cell (0,
(0, 2).
2). It
It is
is not
not necessary
necessary –– aa cell
cell
may be
may be empty.
empty. InIn particular,
particular, you
you should
should note
note that
that aa GridPane
GridPane has has aa static
static method
method thatthat you
you
can use
can use to
to specify
specify aligment
aligment for for aa component
component withinwithin thethe component’s
component’s cell: cell:

GridPane.setHalignment(cmd,
GridPane.setHalignment(cmd, HPos.RIGHT);
HPos.RIGHT);

7.2 EVENTS
7.2 EVENTS
JavaFX has
JavaFX has its
its own
own event
event types,
types, and
and the
the base
base type
type is
is called
called Event.
Event. Examples
Examples of
of specific
specific event
event
types include:
types include:

--- MouseEvent
MouseEvent
--- KeyEvent
KeyEvent
--- DragEvent
DragEvent
--- WindowEvent
WindowEvent
--- ActionEvent
ActionEvent

An event
An event is
is characterized
characterized by
by

1. aa target,
1. target, which
which is
is the
the node
node where
where anan event
event occurs
occurs and
and may
may for
for example
example be
be aa
window, aa scene
window, scene or
or aa node
node
2. aa source,
2. source, which
which is
is the
the one
one that
that has
has generated
generated an
an event
event and
and can,
can, for
for example,
example, be
be
the mouse
the mouse
3. an
3. an event
event type,
type, such
such asas mouse
mouse pressed,
pressed, mouse
mouse released
released and
and so
so on
on

93
91
91
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

When an event occurs, one talks about an event dispatch chain, which is the route from the
stage to that node. Is it a Circle node, for example, it could be

Stage – Scene – Group – Circle

When an event occurs, it is sent to all nodes in its dispatch chain from top to bottom. If
there is a node that has registered a filter for that event, this will be done, after which the
event will be sent to its target node where it will be processed if there is an event handler.
This phase is called the Event Capturing Phase. After that, the event will follow the way
back, and for each node it will be processed if there is a handler assigned. This phase is
called the Event Bubbling Phase. An event can thus result in that multiple event handlers
are performed and event handlers during the capturing phase are called filters while event
handlers during the bubbling phase are called handlers.

When an event follows the dispatch chain, it can at any time be stopped by the method
consume(), which means that the event will not be forwarded in the chain. As an example,
I will show a program EventPhaseProgram that creates the following scene graph:

94
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

where under VBox there are 14 nodes. If you opens the program you get the window:

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

95
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components

For
For example,
example, ifif you
you click
click aa location
location in
in the
the green
green area,
area, the
the following
following is
is written
written on
on standard
standard
output:
output:

Stage – capturing
Sceen – capturing
BorderPane – capture
StackPane – capture
Rectangle – capture
Rectangle – bubbling
StackPane – bubbling
BorderPane – bubbling
Sceen – bubbling
Stage – bubbling

Here
Here you
you can
can see
see how
how the
the event
event of
of mouse
mouse clicks
clicks has
has been
been processed
processed all
all the
the way
way through
through
the
the dispatch chain and back again. The meaning with the checkboxes of the window is
dispatch chain and back again. The meaning with the checkboxes of the window is that
that
you
you check
check where
where the
the processing
processing of
of an
an event
event should
should be
be interrupted.
interrupted. For
For example,
example, checking
checking
Filter
Filter Scene
Scene and
and clicking
clicking the
the green
green rectangle
rectangle again
again gives
gives you
you the
the result:
result:

Stage – capturing
Sceen – capturing

You are
You are encouraged
encouraged to
to test
test the
the program
program and
and what
what happens
happens when
when you
you click
click the
the mouse
mouse on
on
the different
the different nodes
nodes depending
depending on on which
which checkboxes
checkboxes are
are selected.
selected.

Then there
Then there is
is the
the code:
code:

public class EventPhaseProgram extends Application


{
private CheckBox filterStage = new CheckBox("Stage");
private CheckBox filterScene = new CheckBox("Scene");
private CheckBox filterBorder = new CheckBox("BorderPane");
private CheckBox filterPane = new CheckBox("StackPane");
private CheckBox filterRect = new CheckBox("Rectangle");
private CheckBox filterCirc = new CheckBox("Circle");
private CheckBox handleStage = new CheckBox("Stage");
private CheckBox handleScene = new CheckBox("Scene");
private CheckBox handleBorder = new CheckBox("BorderPane");
private CheckBox handlePane = new CheckBox("StackPane");
private CheckBox handleRect = new CheckBox("Rectangle");
private CheckBox handleCirc = new CheckBox("Circle");

@Override
public void start(Stage stage)
{

94
96
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH14: DEVELOPMENT
JAVAFX: OF APPLICATIONS
SOFTWARE DEVELOPMENT Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

stage.setTitle("Event phase");
stage.addEventFilter(MouseEvent.MOUSE_CLICKED,
new Handler("\nStage – capturing", filterStage));
stage.addEventHandler(MouseEvent.MOUSE_CLICKED,
new Handler("Stage – bubbling", handleStage));
stage.setScene(createScene(createBorder(createPane(createRect(),
createCircle(), createButton()), createPanel())));
stage.show();
}

private Scene createScene(Pane root)


{
Scene scene = new Scene(root, 400, 360);
scene.addEventFilter(MouseEvent.MOUSE_CLICKED,
new Handler("Sceen – capturing", filterScene));
scene.addEventHandler(MouseEvent.MOUSE_CLICKED,
new Handler("Sceen – bubbling", handleScene));
return scene;
}

private Pane createBorder(Pane pane1, Pane pane2)


{
BorderPane pane = new BorderPane(null, null, pane2, null, pane1);
pane.setPadding(new Insets(20, 20, 20, 20));
pane.addEventFilter(MouseEvent.MOUSE_CLICKED,
new Handler("BorderPane – capture", filterBorder));
pane.addEventHandler(MouseEvent.MOUSE_CLICKED,
new Handler("BorderPane – bubbling", handleBorder));
return pane;
}

private VBox createPanel()


{
VBox pane = new VBox();
pane.setSpacing(5);
pane.getChildren().add(new Label("Filter"));
pane.getChildren().addAll(filterStage, filterScene, filterBorder, filterPane,
filterRect, filterCirc);
pane.getChildren().add(new Label("Handler"));
pane.getChildren().addAll(handleStage, handleScene, handleBorder, handlePane,
handleRect, handleCirc);
return pane;
}

private Pane createPane(Rectangle rect, Circle circle, Button cmd)


{
StackPane pane = new StackPane(rect, circle, cmd);
pane.addEventFilter(MouseEvent.MOUSE_CLICKED,
new Handler("StackPane – capture", filterPane));

95
97
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH14: DEVELOPMENT
JAVAFX: OF DEVELOPMENT
SOFTWARE APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

pane.addEventHandler(MouseEvent.MOUSE_CLICKED,
new Handler("StackPane – bubbling", handlePane));
return pane;
}

private Button createButton()


{
Button cmd = new Button("Click");
cmd.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
new Alert(Alert.AlertType.INFORMATION,
"You have clicked the button!").showAndWait();
}
});
return cmd;
}

private Circle createCircle()


{
Circle circle = new Circle(20, 20, 100, Color.RED);

98
96
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

circle.addEventFilter(MouseEvent.MOUSE_CLICKED,
new Handler("Circle – capture", filterCirc));
circle.addEventHandler(MouseEvent.MOUSE_CLICKED,
new Handler("Circle – bubbling", handleCirc));
return circle;
}

private Rectangle createRect()


{
Rectangle rect = new Rectangle(0, 0, 220, 220);
rect.setFill(Color.GREEN);
rect.addEventFilter(MouseEvent.MOUSE_CLICKED,
new Handler("Rectangle – capture", filterRect));
rect.addEventHandler(MouseEvent.MOUSE_CLICKED,
new Handler("Rectangle – bubbling", handleRect));
return rect;
}

public static void main(String[] args)


{
launch(args);
}

class Handler implements EventHandler<MouseEvent>


{
private String text;
private CheckBox chkBox;

public Handler(String text, CheckBox chkBox)


{
this.text = text;
this.chkBox = chkBox;
}

@Override
public void handle(MouseEvent e)
{
System.out.println(text);
if (chkBox.isSelected()) e.consume();
}
}
}

First, 12 CheckBox components are created, where the 6 first are to be used for the filters
First, 12 CheckBox components are created, where the 6 first are to be used for the filters
(capturing phase), while the 6 next are to be used for the handlers (bubbling phase). If
(capturing phase), while the 6 next are to be used for the handlers (bubbling phase). If
you consider the method start(), this time, both a filter and a handler are assigned to the
you consider the method start(), this time, both a filter and a handler are assigned to the
Stage node – the node is the top of the scene graph. A filter associated with the method
Stage node – the node is the top of the scene graph. A filter associated with the method

99
97
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA JAVAFX:
WITH
WITH 14: DEVELOPMENT
JAVAFX: SOFTWARE
SOFTWAREOF APPLICATIONS
DEVELOPMENT
DEVELOPMENT Components
Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

addEventFilter(), while a handler is associated with the method addEventHandler(). In either


addEventFilter(), while a handler is associated with the method addEventHandler(). In either
case, an event handler is associated for mouse clicked, such as:
case, an event handler is associated for mouse clicked, such as:
stage.addEventFilter(MouseEvent.MOUSE_CLICKED, new Handler("…", filterStage));
stage.addEventFilter(MouseEvent.MOUSE_CLICKED, new Handler("…", filterStage));

where the first parameter indicates which event to be listened to while the other is the event
where
where the
the first
first parameter
parameter indicates
indicates which
which event
event toto be
be listened
listened to
to while
while the
the other
other isis the
the event
event
handler, there is an object that (in this case) implements the interface EventHandler<MouseEvent>.
handler,
handler,there
thereisisan
anobject
objectthat
that(in
(inthis
thiscase)
case)implements
implementsthe theinterface
interfaceEventHandler<MouseEvent>.
EventHandler<MouseEvent>.
Such an object is defined by the class Handler, which is an inner class where the constructor
Such
Such anan object
object isis defined
defined byby the
the class
class Handler,
Handler, which
which isis an
an inner
inner class
class where
where the
the constructor
constructor
has the text to be printed on the screen as a parameter, and a reference to the CheckBox to
has
has the
the text
text to
to be
be printed
printed onon the
the screen
screen asas aa parameter,
parameter, andand aa reference
reference to
to the
the CheckBox
CheckBox to to
be tested. The class should implement the method:
be
be tested.
tested. The
The class
class should
should implement
implement the the method:
method:
public void handle(MouseEvent e)
public void handle(MouseEvent e)
{
{
}
}

In this case, the method performs a System.out.println(), and then tests whether the appropriate
In this case, the method performs a System.out.println(), and then tests whether the appropriate
CheckBox
In this case,isisthe
selected
method and, if necessary,
performs sets the event asand
a System.out.println(), consumed,
then testswhich means
whether that it will
the appropriate
CheckBox selected and, if necessary, sets the event as consumed, which means that it will
not be forwarded
CheckBox is selected in and,
the dispatch
if chain.
necessary, You
sets the should
event note
as how thewhich
consumed, scenemeans
graph that
is built by
it will
not be forwarded in the dispatch chain. You should note how the scene graph is built by
calling
not be the methods
forwarded in that
the create thechain.
dispatch individual
You nodes. note how the scene graph is built by
should
calling the methods that create the individual nodes.
calling the methods that create the individual nodes.
These methods are all simple and all built in the same way, and you should primarily notice
These methods are all simple and all built in the same way, and you should primarily notice
how tomethods
These assign filters all and handlers
and allto theinindividual nodesandin the should
same way as described
how to assign are filters simple
and handlers built
to the same way,
the individual nodes in youthe same way primarily notice
as described
above.toYou
how assignshould note
filters and createButton(),
handlers to wherethe no filter or
individual handler is attached.
same wayIfIfasyoudescribed
run the
above. You should note createButton(), where no filter nodes in the
or handler is attached. you run the
program
above. Youand click note
should on the button, you will
createButton(), find nothat
filternoorevent handlers are performed in the
program and click on the button, you wherewill find that no handler
event is attached.
handlers If you run
are performed in the
dispatch chain,
program and andon
click thethereason is that
button, you the button
will find instead
that no with
event setOnAction()
handlers are is associatedinwith
performed the
dispatch chain, and the reason is that the button instead with setOnAction() is associated with
an event
dispatch handler of the type EventHandler<ActionEvent>. This means that with the mouse
an eventchain,
handler andofthe thereason is that the button instead withThis
type EventHandler<ActionEvent>. setOnAction()
means thatis with
associated with
the mouse
click,
an the handler
event button willthe take care of the event action and notThis fire a regular
thatmouse event, but
click, the button of will take type EventHandler<ActionEvent>.
care of the event action and not firemeans a regular with the
mouse mouse
event, but
insteadthe
click, anbutton
ActionEvent.
will Also
take note
care of that
the the event
event action handler
and notof fire
the abutton’s
regular ActionEvent
mouse opens
event, but
instead an ActionEvent. Also note that the event handler of the button’s ActionEvent opens
a simpleanmessage
instead box, including
ActionEvent. Also notethe thatsyntax for how
the event to doofitthe
handler in JavaFX. ActionEvent opens
a simple message box, including the syntax for how to do it inbutton’s
JavaFX.
a simple message box, including the syntax for how to do it in JavaFX.
The next example is called KeyEventProgram and opens the following window:
The next example is called KeyEventProgram and opens the following window:
The next example is called KeyEventProgram and opens the following window:

100
98
98
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

If you are in the entry field and enter the key Enter, the green square will rotate and clicking
on the square it will stop the rotation. The code is as follows:

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

101
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

public class KeyEventProgram extends Application


{
private Transition trans;

@Override
public void start(Stage stage)
{
Rectangle rect = createRect();
trans = createRotate(rect);
Group root = new Group(createLabel(), createField(), rect);
Scene scene = new Scene(root, 500, 400);
scene.setFill(Color.BEIGE);
stage.setTitle("Click rectangle to stop");
stage.setScene(scene);
stage.show();
}

private Rectangle createRect()


{
Rectangle rect = new Rectangle(200, 100, 200, 200);
rect.setFill(Color.DARKGREEN);
rect.setOnMouseClicked(e -> trans.stop());
return rect;
}

private Transition createRotate(Shape shape)


{
RotateTransition trans = new RotateTransition(Duration.millis(1000), shape);
trans.setByAngle(360);
trans.setCycleCount(50);
trans.setAutoReverse(true);
return trans;
}

private TextField createField()


{
TextField field = new TextField();
field.setLayoutX(20);
field.setLayoutY(40);
field.setPrefWidth(50);
field.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>()
{
public void handle(KeyEvent e)
{
if (e.getCharacter().charAt(0) == '\r’) trans.play();
e.consume();
}
});
return field;
}

100
102
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

private Label createLabel()


{
Label label = new Label("Enter to start");
label.setLayoutX(20);
label.setLayoutY(20);
return label;
}

public static void main(String[] args)


{
launch(args);
}
}

The class defines a variable for a transition, which is the animation that rotates the square.
It is created by the method createRotate(), which does not contain anything new in terms of
animations. The actual Transition object is created in the method start(). Here you should
also notice how to set the background color for the window. The square is created in the
method createRect(). Here, the method setOnMouseClicked() is used to attach an event handler
for mouse clicks to the square, and you should note how the event handler is defined using
a lambda expression.

Then there is the method createField() that creates the entry field. It is a TextField, and
the most important is the association of the event handler. It is a filter and the handler is
associated for a KeyEvent of the type KEY_TYPED. The handler uses the method getCharacter()
to test what has been entered and has the first character the code 13, it is the Enter key
that is pressed, and if so, the animation will start. For any event, the event is marked as
cosumed so that it is not passed on in the chain, and the effect is that the character for
the key pressed is never displayed in the input field.

The example thus shows how to catch events for mouse and keyboard. In the example,
it happens in two different ways, where in createField() it takes place at low level with
addEventFilter() while in createRect() it occurs using a convenience method. Many of the
JavaFX classes defines event handlers as properties, and you can then register an event handler
using a set method for that convenience method. The goal is to make it easier to associate
event handlers what the following program HandlerProgram should illustrate:

103
101
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

Clicking the Start button starts an animation where the circle moves along the curve and the
animation runs until you click the stop button. If you click on the circle, it changes color.

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

104
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX:
WITH 14: DEVELOPMENT
SOFTWAREOFDEVELOPMENT
APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

public class HandlerProgram extends Application


{
private boolean blue = true;
private Transition trans;

@Override
public void start(Stage stage)
{
Circle circle = createCircle();
Path path = createPath();
trans = createTrans(circle, path);
Group root = new Group(createButton("Start", 20, e -> trans.play()),
createButton("Stop", 120, e -> trans.stop()), path, circle);
Scene scene = new Scene(root, 560, 400);
scene.setFill(Color.BEIGE);
stage.setTitle("Move");
stage.setScene(scene);
stage.show();
}

private Button createButton(String text, int pos,


EventHandler<ActionEvent> handler)
{
Button cmd = new Button(text);
cmd.setLayoutX(pos);
cmd.setLayoutY(20);
cmd.setPrefSize(80, 25);
cmd.setOnAction(handler);
return cmd;
}

private Transition createTrans(Shape shape, Path path)


{
PathTransition trans = new PathTransition();
trans.setDuration(Duration.millis(3000));
trans.setNode(shape);
trans.setPath(path);
trans.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
trans.setCycleCount(50);
trans.setAutoReverse(true);
return trans;
}

private Circle createCircle()


{
Circle circle = new Circle(40, 80, 25, Color.BLUE);
circle.setStrokeWidth(20);
circle.setOnMouseClicked(

105
103
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH 14: DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

e -> { blue = !blue; circle.setFill(blue ? Color.BLUE : Color.RED); });


return circle;
}

private Path createPath()


{
Path path = new Path(new MoveTo(40, 80),
new CubicCurveTo(140, 440, 400, 0, 500, 340));
path.setStroke(Color.DARKGREEN);
path.setStrokeWidth(3);
return path;
}

public static void main(String[] args)


{
launch(args);
}
}

As how to create the animation and the curve there is nothing new and happens in the
As how to create the animation and the curve there is nothing new and happens in the
two methods createTrans() and createRect(). If you consider the method createCircle() that
two methods createTrans() and createRect(). If you consider the method createCircle() that
creates the circle, it associates an event handler for mouse clicks using a convenience method
creates the circle, it associates an event handler for mouse clicks using a convenience method
called setOnMouseClicked(). You should note that the event handler is the parameter and
called setOnMouseClicked(). You should note that the event handler is the parameter and
is a lambda expression.
is a lambda expression.

The method createButton() is used to create a button. It has three parameters, which is the
The method createButton() is used to create a button. It has three parameters, which is the
text of the button, the x-coordinate of the location in the window and the button’s event
text of the button, the x-coordinate of the location in the window and the button’s event
handler. The latter has the type EventHandler<ActionEvent> and is associated with the
handler. The latter has the type EventHandler<ActionEvent> and is associated with the
method setOnActionEvent().
method setOnActionEvent().

7.3 COMPONENTS
7.3 COMPONENTS
Then there are the components (or controls) where JavaFX has many, but the most important
Then there are the components (or controls) where JavaFX has many, but the most important
are the following:
are the following:

Label MenuButton Slider ColorPicker


Label MenuButton Slider ColorPicker
Button MenuItem ScrollPane DatePicker
Button MenuItem ScrollPane DatePicker
TextField Menu ScrollBar ProgressIndicator
TextField Menu ScrollBar ProgressIndicator
PassWordField ContextMenu TabPane ProgressBar
PassWordField ContextMenu TabPane ProgressBar
TextArea Separator SplitPane FileChooser
TextArea Separator SplitPane FileChooser

106
104
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

RadioButton ChoieBox TitlePane HTMLEditor

Hyperlink ComboBox Accordion TableView

CheckBox ListView Pagination TreeView

ToggleButton WebView Tooltip TreeTableView

Some of these components have already been used in the previous examples and the rest
of this section consists of exercises and problems where you should try using the above
components (but not the last three in the last column postponed to the next book). Most
of the components are easy to use and take a good part of the way, as you know it from
Swing. Others are more complex, and on the whole, the following exercises require that
you use the documentation and, if necessary, also find examples and help on the Internet.

107
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

EXERCISE 25
You must write a program that opens the following window:

where there are 4 controls: 1 Label and 3 Button controls. If you click New, the text must
be changed to

Creatring a new document…

and clicking Save should change the text to

Saving…

If you click the Cancel button, the text must be changed to the original text. It is required
that the window must not be resizable, and that there must be shortcuts for all three buttons.

With regard to the green frame, it can be defined with a style. This is the subject of the
next chapter, but you can try and see how far you can come.

EXERCISE 26
You must write an application that opens the following window:

108
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

In the top line there are three Hyperlink controls on the left. A Hyperlink is the same as
a Button, but it is drawn in another way. In this case, the three links must refer to a web
page (you decide which ones). On the right side there is a MenuButton, which is a button
with a dropdown, where you can click on a MenuItem control. In this case, there must be
three items, each of which refers to a web page (which you decide).

Center, there must be a WebView control, which is a control that can open and display a
web page.

At the bottom there are three ToggleButton controls in a group and a Label. When you
click a button, the Label control must be updated with the button’s text, if it is clicked
and otherwise the text None.

Note that the commands at the top and the commands at the bottom have nothing to do
with each other, and the goal is only to illustrate typical controls.

EXERCISE 27
Write a program that uses a ChoiceBox control:

You must be able to select a person from the dropdown list when a person is represented by
an object of the type Person. It must be a simple model class that represents a person by a
name and a job title. It is a requirement that the Person class must not have any toString()
method, and instead, a converter must be associated with the ChoiceBox control. After
selecting a person, the name and the job title must be displayed with a Label:

109
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

When you click the Clear button, this label must be blanked and no person in the ChoiceBox
control must be selected.

EXERCISE 28
You must write the same program as in the previous exercise, but with one difference:
Instead of using a ChoiceBox, you use a ComboBox.

Once you have written the program, try to investigate what the difference is between a
ChoiceBox and a ComboBox.

110
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

PROBLEM 3
From Swing you know the component JList, which is a list box and is one of the widely
used components. In JavaFX, it is replaced by a ListView, which is a much more advanced
component with many new options, which uses multiple help classes. You must write
an application that opens the following window, where the window shows four ListView
controls (actually 5), each ListView showing 10 Person objects where Person is the class from
exercise 27.

1. The ListView control in the upper left corner should show how to select items. You
can select an item with the mouse and select an item using the top 5 buttons. Each
time you select an item, the blank ListView must show which items are selected.
2. The ListView control in the upper right corner should show how to edit a Person
object. If you double-click on a person, the list box must open a field so you can
edit the content (it is built into the component). Under the control there is a
TextField that will be used to add a new Person object to the list.

111
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

3. The ListView control at the bottom left should show items where each element is a
ChoiceBox, from which you can update the item by selecting another Person object
(it is also built into the component).
4. Finally, the last ListView shows the items as CheckBox controls (it is also incorporated
into the ListView component). If you click on the button, the program must open
a message box that displays the objects that are selected (by the checkboxes).

The task requires you to examine the documentation to find out what to write, and maybe
you can also can find help online.

EXERCISE 29
JavaFX has a component called ColorPicker, which is a relatively complicated component
for selecting a color. On the other hand, the component is both flexible and easy to use.
You must write a program that opens a window where you can choose a color used to
color a rectangle:

EXERCISE 30
JavaFX has a good DatePicker control that can be used to select a date. You must write a
program that opens the following window, where November 15, 2017 was selected:

After the date is selected, the bottom Label must be uploaded.

112
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

EXERCISE 31
JavaFX has a progress bar like Swing, but there is also a ProgressIndicator, and the difference
is how the two components are drawn. The ProgressIndicator control is bass class for
ProgressBar. A progress component is updated in the same way as in Swing using a thread
represented by a Task object contained in the javafx.concurrent package. You must write a
program that shows a ProgressIndicator and a ProgressBar, both of which can be started (and
stopped) by clicking a button:

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

113
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

and below is the window after clicking on both buttons:

and below the window after the two progress components are completed:

EXERCISE 33
You must write a program that opens the following window, that has a Label, a TextField
and two Button controls:

The buttons do not need an action, but the input field and the buttons must have a Tooltip.
Here it is interesting that you can attach a style to a tooltip, where styles is the subject of
the next chapter.

114
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

EXERCISE 34
Write a program that has a window with two TextArea controls located in a SplitPane:

PROBLEM 4
In this task you should work with menus in JavaFX. You must write an application that
opens the following window:

115
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

The window has a menubar with two menus, and the window itself (center) has a Canvas
object. The first menu must have the following functions:

116
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

If you click on one of the three top menu items, a dark green shape with a black border
in the window should appear, for example:

The fourth menu item must clear the window, while the last one should close the program.
The Options menu has a menu item as well as a Slider :

The first menu item must indicate if the circumference of the shape is to be drawn while
the slider indicates the size of the perimeter. If you move the slider, the perimeter of any
shape should be updated.

If you right click on the canvas object you should get a context menu:

117
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

and clicking on one of the two menu items, a ColorPicker object should appear at the
bottom of the window, so you can choose one of the two colors:

As a last requirement, shortcut keys must be available for all menu items, and accelerator
keys must be defined for the three shapes.

EXERCISE 35
You must write an application that opens the following window:

and thus a program that uses tabs (two tabs). On the first one, you must enter a name and
a registration date, while on the other you can enter the address and an email address. If
you click on the button, you must get a message box that shows the data entered:

118
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

EXERCISE 36
JavaFX has a control called HTMLEditor, which is a complete HTML editor. You must write
an application that opens the following window where you can edit a HTML document:

The program must have buttons so you can load and save an HTML document in a local file.

Need help with your


dissertation?
Get in-depth feedback & advice from experts in your
topic area. Find out what you can do to improve
the quality of your dissertation!

Get Help Now

Go to www.helpmyassignment.co.uk for more info

119
JAVA
JAVA14:
14:DEVELOPMENT
DEVELOPMENTOF
OFAPPLICATIONS
APPLICATIONS
WITH
WITHJAVAFX:
JAVAFX:SOFTWARE
SOFTWAREDEVELOPMENT
DEVELOPMENT Components
Components

7.4 DIALOGS
7.4 DIALOGS
You
You can
can also
also use
use dialog
dialog boxes,
boxes, and
and there
there are
are dialogs
dialogs asas in
in Swing
Swing there
there are
are ready
ready toto use
use
classes
classes that
that can
can be
be used
used immediately
immediately and,
and, and
and onon the
the other
other hand,
hand, there
there are
are dialog
dialog boxes
boxes
that
thatare
arecustom.
custom.TheThesimplest
simplestisisan
anAlert
Alertthat
thatcorresponds
correspondsto toaaMessageDialog
MessageDialogin inSwing.
Swing.TheThe
AlertProgram
AlertProgram application
application opens
opens the
the following
following window:
window:

IfIfyou
youclick
clickon
onthe
theInfo
Infobutton,
button,you youget
getthethemessage
messagebox boxbelow
belowthat
thatshows
showsaasimple
simplemessage
message
and
and clicking
clicking on
on the
the Save
Save button,
button, you
you may
may receive
receive aa corresponding
corresponding message
message box
box (but
(but with
with
an
an error
error message)
message) and
and finally
finally the
the last
last button
button will
will result
result in
in aa message
message box
box with
with aa warning,
warning,
where
where youyou will
will be
be asked
asked ifif you
you want
want to to delete
delete the
the entry
entry field:
field:

package alertprogram;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.*;
import javafx.scene.text.*;
import javafx.scene.text.Text;
import javafx.scene.paint.Color;
import javafx.scene.control.*;
import javafx.geometry.*;
import javafx.event.*;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import java.util.Optional;

120
118
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVAJAVAFX:
WITH 14: DEVELOPMENT
SOFTWAREOF APPLICATIONS
DEVELOPMENT Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

public class AlertProgram extends Application


{
private TextField txtField = new TextField();
private Button cmdInfo;
private Text status = new Text();

@Override
public void start(Stage stage)
{
txtField.setPromptText("Enter some text and save.");
status.setFont(Font.font("Arial", FontWeight.NORMAL, 20));
VBox vbox = new VBox(20, txtField, createCommands(), status);
vbox.setPadding(new Insets(20, 20, 20, 20));;
Scene scene = new Scene(vbox, 400, 180);
stage.setTitle("AlertProgram");
stage.setScene(scene);
stage.show();
cmdInfo.requestFocus();
}

private Pane createCommands()


{
HBox pane = new HBox(10, cmdInfo = createButton("Info", new InfoListener()),
createButton("Save", new SaveListener()), createButton("Clear",
new ClearListener()));
pane.setAlignment(Pos.CENTER_RIGHT);
return pane;
}

private Button createButton(String text, EventHandler<ActionEvent> handler)


{
Button cmd = new Button(text);
cmd.setOnAction(handler);
return cmd;
}

private class InfoListener implements EventHandler<ActionEvent>


{
@Override
public void handle(ActionEvent e)
{
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("About this program");
alert.setHeaderText("How to use this program");
alert.setContentText(
"Enter a text at least 5 characters\nand then click Save.");
alert.show();
}
}

119
121
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: OFDEVELOPMENT
SOFTWARE APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

private class SaveListener implements EventHandler<ActionEvent>


{
@Override
public void handle(ActionEvent e)
{
String txt = txtField.getText().trim();
String msg = "Text is saved";
boolean valid = true;
if ((txt.isEmpty()) || (txt.length() < 5))
{
valid = false;
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error message");
alert.setContentText(
"Text should be at least 5 characters long.\nEnter a valid text and save. ");
alert.showAndWait();
msg = "Invalid text entered";
}
status.setText(msg);
status.setFill(valid ? Color.DARKGREEN : Color.DARKRED);
if (!valid) txtField.requestFocus();
}
}

Brain power By 2020, wind could provide one-tenth of our planet’s


electricity needs. Already today, SKF’s innovative know-
how is crucial to running a large proportion of the
world’s wind turbines.
Up to 25 % of the generating costs relate to mainte-
nance. These can be reduced dramatically thanks to our
systems for on-line condition monitoring and automatic
lubrication. We help make it more economical to create
cleaner, cheaper energy out of thin air.
By sharing our experience, expertise, and creativity,
industries can boost performance beyond expectations.
Therefore we need the best employees who can
meet this challenge!

The Power of Knowledge Engineering

Plug into The Power of Knowledge Engineering.


Visit us at www.skf.com/knowledge

120
122
JAVA 14:
JAVA 14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA
WITH14:
WITH DEVELOPMENT
JAVAFX:
JAVAFX: OFDEVELOPMENT
SOFTWARE
SOFTWARE APPLICATIONS
DEVELOPMENT Components
Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

private class ClearListener implements EventHandler<ActionEvent>


private
{ class ClearListener implements EventHandler<ActionEvent>
{ @Override
@Override
public void handle(ActionEvent e)
public
{ void handle(ActionEvent e)
{ Alert alert = new Alert(AlertType.CONFIRMATION);
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Warning message");
alert.setTitle("Warning message");
alert.setContentText("Are you sure you want to delete the text field");
alert.setContentText("Are you sure you want to delete the text field");
Optional<ButtonType> result = alert.showAndWait();
Optional<ButtonType> result
if ((result.isPresent()) && =(result.get()
alert.showAndWait();
== ButtonType.OK))
if
{ ((result.isPresent()) && (result.get() == ButtonType.OK))
{ txtField.clear();
txtField.clear();
status.setText("");
status.setText("");
cmdInfo.requestFocus();
}cmdInfo.requestFocus();
}}
} }
}

public static void main(String [] args)


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

The buttons
The buttons areare created
created in
in the
the method
method createCommands(),
createCommands(), and and here
here are
are the
the interesting
interesting the
the
The buttons are created in the method createCommands(), and here are the interesting the
ActionEvent listeners,
ActionEvent listeners, which
which areare defined
defined asas classes
classes at
at the
the end
end of
of the
the program.
program. TheThe InfoListener
InfoListener
ActionEvent listeners, which are defined as classes at the end of the program. The InfoListener
class creates
class creates anan event
event object
object for
for the
the Info
Info button,
button, andand in in the
the handler
handler isis created
created anan Alert
Alert object
object
class creates an event object for the Info button, and in the handler is created an Alert object
of the
of the type
type AlertType.INFORMATION
AlertType.INFORMATION and and the
the result
result isis the
the dialog
dialog box
box shown
shown above.
above. You
You
of the type AlertType.INFORMATION and the result is the dialog box shown above. You
must note
must note how
how thethe dialog
dialog box
box isis otherwise
otherwise initialized
initialized and and how
how the
the individual
individual messages
messages
must note how the dialog box is otherwise initialized and how the individual messages
appear in
appear in the
the message
message box.
box. The
The dialog
dialog opens
opens with
with thethe method
method show().
show(). The
The method
method isis not
not
appear in the message box. The dialog opens with the method show(). The method is not
blocking and
blocking and thethe program
program isis not
not waiting
waiting for
for aa return
return value.
value.
blocking and the program is not waiting for a return value.
The SaveListener
The SaveListener class class defines
defines aa listener
listener to
to the
the Save
Save button
button and
and simulates
simulates that
that the
the entered
entered
The SaveListener class defines a listener to the Save button and simulates that the entered
text isis saved.
text saved. ItIt tests
tests the
the text
text length
length and
and isis the
the length
length less
less than
than 5,
5, an
an alert
alert similar
similar to
to the
the
text is saved. It tests the text length and is the length less than 5, an alert similar to the
above opens.
above opens. The
The difference
difference isis the
the type
type asas here
here isis AlertType.ERROR
AlertType.ERROR corresponding
corresponding to to an
an
above opens. The difference is the type as here is AlertType.ERROR corresponding to an
error message,
error message, and and then
then the
the dialog
dialog opens
opens but
but instead
instead with
with the
the method
method showAndWait().
showAndWait(). ThisThis
error message, and then the dialog opens but instead with the method showAndWait(). This
means that
means that the
the message
message boxbox isis blocking
blocking andand thethe following
following statement
statement
means that the message box is blocking and the following statement
msg = "Invalid text entered";
msg = "Invalid text entered";

will only
will only be
be executed
executed after
after the
the dialog
dialog box
box isis closed.
closed.
will only be executed after the dialog box is closed.
Thelast
The lastlistener
listenerclass
classisissimilar
similarto
tothe
theothers,
others,but
butthis
thistime
timeisisthe
thetype
typeAlertType.CONFIRMATION
AlertType.CONFIRMATION
The last listener class is similar to the others, but this time is the type AlertType.CONFIRMATION
that opens
that opens aa dialog
dialog box
box with
with two
two buttons,
buttons, where
where thethe user
user must
must select
select YES
YES or
or NO.
NO. ItIt also
also
that opens a dialog box with two buttons, where the user must select YES or NO. It also

121
123
121
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components

opens
opens with
with showAndWait()
showAndWait() and
and you
you should
should note
note that
that this
this time
time there
there isis aa return
return value
value and
and
how
how this
this value
value isis tested.
tested.

There
There also
also isis aa ChoiceDialog,
ChoiceDialog, where
where the
the user
user can
can choose
choose aa value
value between
between several
several options.
options.
The
The program
program ChoiceProgram
ChoiceProgram opens
opens aa window
window with
with aa button
button and
and clicking
clicking on
on the
the button
button
gives
gives you
you the
the following
following dialog
dialog box:
box:

where
where in
in aa dropdown
dropdown you you can
can choose
choose aa text
text (in
(in this
this case
case the
the name
name of
of aa Danish
Danish king).
king). If
If
you
you click
click OK,
OK, the
the selected
selected name
name will
will be
be returned
returned to
to the
the application
application where
where itit appears
appears in
in the
the
window.
window. The
The code
code isis as
as follows:
follows:

public class ChoiceProgram extends Application


{
private List<String> dialogData = Arrays.asList("Gorm den Gamle",
"Harald Blåtand", "Svend Tveskæg", "Harald d. 2.", "Knud den Store");
private Text status = new Text();

@Override
public void start(Stage stage)
{
Button cmd = new Button("Get a King");
cmd.setOnAction(e -> showDialog());
HBox command = new HBox(cmd);
command.setAlignment(Pos.CENTER);
status.setFont(Font.font("Arial", FontWeight.NORMAL, 20));
status.setFill(Color.DARKGREEN);
HBox message = new HBox(status);
message.setAlignment(Pos.CENTER);
VBox root = new VBox(30, command, message);
root.setPadding(new Insets(20, 20, 20, 20));
Scene scene = new Scene(root, 400, 150);
stage.setTitle("ChoiceProgram");
stage.setScene(scene);
stage.show();
}

124
122
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

private void showDialog()


{
ChoiceDialog<String> dialog =
new ChoiceDialog<String>(dialogData.get(0), dialogData);
dialog.setTitle("Danish Kings");
dialog.setHeaderText("Choice a king");
Optional<String> result = dialog.showAndWait();
String selected = "cancelled…";
if (result.isPresent()) selected = result.get();
status.setText(selected);
}

public static void main(String [] args)


{
launch(args);
}
}

Initially,
Initially, aa list
list named
named dialogData,
dialogData, which
which contains
contains the
the names
names of
of 55 Danish
Danish kings,
kings, is
is defined.
defined.
The
The method
method start()
start() is
is simply
simply and
and build
build aa scene
scene graph
graph containing
containing aa button
button and
and aa Text
Text control.
control.
The
The button’s event handler calls the method showDialog(), which creates a dialog of
button’s event handler calls the method showDialog(), which creates a dialog of the
the
type ChoiceDialog. The parameters of the constructor are the data to be displayed
type ChoiceDialog. The parameters of the constructor are the data to be displayed in the in the

125
123
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components

dropdown
dropdown field
field and
and which
which one
one should
should be be selected
selected by
by default.
default. Otherwise,
Otherwise, you
you should
should notice
notice
how
how to
to get
get the
the return
return value
value and
and test
test it.
it.

As
As the
the last
last of
of the
the standard
standard dialog
dialog boxes,
boxes, you
you have
have aa TextInputDialog
TextInputDialog that
that isis used
used to
to enter
enter
aa text.
text. The
The program
program InputProgram
InputProgram opens
opens just
just like
like the
the previous
previous program
program aa window
window with
with aa
button
button and
and clicking
clicking on
on the
the button
button gives
gives you
you aa dialog
dialog box
box where
where you
you can
can enter
enter aa text:
text:

The
The program
program isis basically
basically identical
identical to
to the
the previous
previous one,
one, so
so II would
would like
like only
only to
to show
show the
the
method
method called
called from
from the
the event
event handler
handler forfor the
the button,
button, and
and compared
compared toto the
the previous
previous example,
example,
there
there isis not
not much
much toto explain,
explain, the
the fact
fact that
that the
the type
type of
of the
the dialog
dialog box
box isis now
now TextInputDialog:
TextInputDialog:

private void showDialog()


{
TextInputDialog dialog = new TextInputDialog("A name?");
dialog.setTitle("Enter text");
dialog.setHeaderText("Enter some text.");
Optional<String> result = dialog.showAndWait();
status.setText(result.isPresent() ? result.get() : "");
}

As the last example in this section, the following application opens two custom dialogs. The
As the last example in this section, the following application opens two custom dialogs. The
program is called DialogProgram, and if you run the program, you get the following window:
program is called DialogProgram, and if you run the program, you get the following window:

If you click on the button at the top, you will get a dialog box where you should enter the
If you click on the button at the top, you will get a dialog box where you should enter the
name and job title of a person and choose a date (which can be interpreted as birthday,
name and job title of a person and choose a date (which can be interpreted as birthday,
appointment date or something else):
appointment date or something else):

126
124
JAVA 14:
JAVA 14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH JAVAFX:
WITH JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Components
Components

IfIf you
you click
click the
the bottom
bottom button,
button, the
the program
program opens opens another
another dialog
dialog box
box that
that shows
shows the
the
persons entered
persons entered in
in the
the first
first dialog
dialog box
box (here
(here itit isis after
after two
two persons
persons are
are entered):
entered):

The program
The program looks
looks like
like aa program
program that
that I’ve
I’ve seen
seen before
before in
in connection
connection with
with Swing
Swing (the
(the book
book
Java 2).
Java 2). AA person
person isis defined
defined by
by aa simple
simple model
model class:
class:

package dialogprogram;

import java.time.*;

public class Person


{
private String name;
private String job;
private LocalDate date;

125
127
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

@Override
public String toString()
{
return String.format("%s, %s [%s]", name, job, date.toString());
}
}

Then there is the code of the program:

public class DialogProgram extends Application


{
private List<Person> persons = new ArrayList();

@Override
public void start(Stage stage)
{
VBox root = new VBox(20, createButton("Enter person", 150, e -> enterDialog()),
createButton("Show persons", 150, e -> showDialog()));
root.setAlignment(Pos.TOP_CENTER);
root.setPadding(new Insets(20, 20, 20, 20));;
Scene scene = new Scene(root, 300, 150);
stage.setTitle("DialogProgram");

128
126
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

stage.setScene(scene);
stage.show();
}

private Button createButton(String text, double width,


EventHandler<ActionEvent> handler)
{
Button cmd = new Button(text);
cmd.setPrefSize(width, 25);
cmd.setOnAction(handler);
return cmd;
}

private void enterDialog()


{
Dialog<Person> dialog = new Dialog();
dialog.setTitle("Enter person");
dialog.setResizable(false);
TextField name = new TextField();
TextField job = new TextField();
DatePicker date = new DatePicker();
name.setPrefWidth(300);
job.setPrefWidth(300);
date.setPrefWidth(150);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(20);
grid.setPadding(new Insets(10, 10, 10, 10));
grid.add(new Label("Name"), 0, 0);
grid.add(name, 1, 0);
grid.add(new Label("Job"), 0, 1);
grid.add(job, 1, 1);
grid.add(new Label("Date"), 0, 2);
grid.add(date, 1, 2);
dialog.getDialogPane().setContent(grid);
dialog.getDialogPane().getButtonTypes().add(
new ButtonType("OK", ButtonData.OK_DONE));
dialog.getDialogPane().getButtonTypes().add(
new ButtonType("Cancel", ButtonData.CANCEL_CLOSE));
dialog.setResultConverter(new Callback<ButtonType, Person>()
{
@Override
public Person call(ButtonType b)
{
return b.getButtonData() == ButtonData.OK_DONE ?
new Person(name.getText(), job.getText(), date.getValue()) : null;
}
});

129
127
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS Components
WITH JAVAFX: SOFTWARE DEVELOPMENT Components

Optional<Person> result = dialog.showAndWait();


if (result.isPresent()) persons.add(result.get());
}

private void showDialog()


{
ListView<Person> view = new ListView();
view.setPrefSize(400, 300);
view.getItems().addAll(persons);
BorderPane pane = new BorderPane(view);
Dialog<List<Person>> dialog = new Dialog();
dialog.setTitle("Persons");
dialog.setHeaderText("You have entered the following persons:");
dialog.setResizable(true);
dialog.getDialogPane().setContent(pane);
dialog.getDialogPane().getButtonTypes().add(
new ButtonType("Close", ButtonData.CANCEL_CLOSE));
dialog.show();
}

public static void main(String [] args)


{
launch(args);
}
}

At
At the
the start
start of
of the
the program,
program, aa list
list is
is defined
defined for
for Person
Person objects,
objects, which
which are
are the
the persons
persons created
created
in
in the input dialog. The method start() is trivial and the only thing to note is which event
the input dialog. The method start() is trivial and the only thing to note is which event
handlers are associated with the two buttons. The first calls the method enterDialog(),
handlers are associated with the two buttons. The first calls the method enterDialog(), which which
creates
creates an
an object
object ofof the
the type
type Dialog
Dialog to to Person
Person objects.
objects. The The parameter
parameter type
type Person
Person specifies
specifies
which
which object is returned if the dialog box ends by clicking OK. Next, the contents of
object is returned if the dialog box ends by clicking OK. Next, the contents of the
the
dialog box must be defined, and that happens by a GridPane, which
dialog box must be defined, and that happens by a GridPane, which laid out the dialog laid out the dialog
box
box components,
components, and and this
this Pane
Pane isis assigned
assigned thethe dialog
dialog boxbox asas follows:
follows:

dialog.getDialogPane().setContent(grid);

The next step defines which buttons the dialog should have, and then is defined how to
The next step defines which buttons the dialog should have, and then is defined how to
click on OK to create a Person object, which must be the return value of the dialog box.
click on OK to create a Person object, which must be the return value of the dialog box.

The other dialog box is basically built in exactly the same way, but this time with a
The other dialog box is basically built in exactly the same way, but this time with a
BorderPane. The main difference is that there is no return value this time. You should note
BorderPane. The main difference is that there is no return value this time. You should note
that this dialog box has a header text, while the first one did not, and what a header text
that this dialog box has a header text, while the first one did not, and what a header text
means for the result.
means for the result.

130
128
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Styling

8 STYLING
From web applications you know cascading style sheets, and you can also use it in JavaFX.
The idea is the same as for web application, namely to separate the definition of windows
and their content from the presentation so that you can change the look and feel of a
program without changing the code. On the other hand, the syntax is a little different, and
as for web applications, the biggest challenge is to learn how styles can be written and what
they are called. The subject appears best with an example, and the program StyleProgram
opens the following window:

Challenge the way we run

EXPERIENCE THE POWER OF


FULL ENGAGEMENT…

RUN FASTER.
RUN LONGER.. READ MORE & PRE-ORDER TODAY
RUN EASIER… WWW.GAITEYE.COM

1349906_A6_4+0.indd 1 22-08-2014 12:56:57

131
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT stylIng
WITH JAVAFX: SOFTWARE DEVELOPMENT stylIng
Styling

where the
where the window
window contains
contains two
two Label
Label controls,
controls, two
two TextField
TextField controls
controls and
and two
two Button
Button
controls. For
controls. For all
all 6
6 components
components there
there is
is aa style
style attached.
attached. For
For the
the TextField
TextField and
and Button
Button controls,
controls,
it happens
it happens in
in aa style
style sheet,
sheet, which
which is
is aa file
file named
named styles.css:
styles.css:

.button
.button {{
-fx-background-color: red;
-fx-background-color: red;
-fx-text-fill: white;
-fx-text-fill: white;
}
}
.text-field {
.text-field {
-fx-border-width: 3;
-fx-border-width: 3;
-fx-border-color: blue;
-fx-border-color: blue;
}
}
.border
.border {{
-fx-padding: 20;
-fx-padding: 20;
-fx-border-style: solid inside;
-fx-border-style: solid inside;
-fx-border-width: 5;
-fx-border-width: 5;
-fx-border-insets: 25;
-fx-border-insets: 25;
-fx-border-radius: 5;
-fx-border-radius: 5;
-fx-border-color: gray;
-fx-border-color: gray;
}
}

Here
Here are
are three
three styles
styles defined.
defined. InIn the
the same
same way way as as for
for web
web pages,
pages, aa style
style is
is defined
defined with
with aa
selector
selector that
that starts
starts with
with aa point
point followed
followed by by the
the type
type onon the
the node
node inin the
the scene
scene graph,
graph, which
which
should have that style – but with the class name written in lowercase.
should have that style – but with the class name written in lowercase. The first, therefore,The first, therefore,
defines
defines aa style
style for
for Button
Button nodes.
nodes. Here,
Here, twotwo style
style attributes
attributes are
are defined,
defined, and
and the
the difficulty
difficulty is
is
of course to know which attributes can be specified, but in general, you can
of course to know which attributes can be specified, but in general, you can associate a style associate a style
value
value with
with any
any of
of the
the class’s
class’s properties.
properties. Here
Here is is the
the syntax
syntax that
that if
if there
there is
is aa property
property called
called
backgroundColor,
backgroundColor, the style attribute is named -fx-background-color. That is, if the name of
the style attribute is named -fx-background-color. That is, if the name of
an attribute consists of two words, the last one starting with a capital letter,
an attribute consists of two words, the last one starting with a capital letter, it is all written it is all written
in
in lowercase
lowercase letters
letters and
and with
with aa hyphen
hyphen is is inserted
inserted between
between thethe words.
words. The
The same
same syntax
syntax is
is
used for a selector, and a selector for the class TextField is
used for a selector, and a selector for the class TextField is written as: written as:

.text-field
.text-field

You
You can
can also
also have
have aa custom
custom selector,
selector, what
what the
the last
last style
style is
is an
an example
example of.
of. It
It defines
defines aa style
style
for
for the gray frame in the window, and when you see the individual attributes, it is easy
the gray frame in the window, and when you see the individual attributes, it is easy
enough
enough to understand the meaning. In practice, of course, it is more difficult to find out
to understand the meaning. In practice, of course, it is more difficult to find out
what to write, and it is important to note that NetBeans knows JavaFX
what to write, and it is important to note that NetBeans knows JavaFX style sheets andstyle sheets and
which
which attributes
attributes are
are available.
available.

With
With respect
respect to
to the
the syntax,
syntax, the
the following
following applies
applies to
to values
values of
of the
the individual
individual attributes:
attributes:

130
130
132
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF APPLICATIONS
OFDEVELOPMENT
APPLICATIONS
JAVA
JAVA 14:
WITH
WITH DEVELOPMENT
JAVAFX:
JAVAFX:
14: SOFTWARE
SOFTWARE
DEVELOPMENT OF APPLICATIONS
DEVELOPMENT
OFDEVELOPMENT
APPLICATIONS Styling
stylIng
JAVA
WITH
JAVA
WITH 14:
14: DEVELOPMENT
JAVAFX: SOFTWARE
DEVELOPMENT
JAVAFX: SOFTWAREOF
OF APPLICATIONS
APPLICATIONS
DEVELOPMENT stylIng
stylIng
WITH JAVAFX:
WITH JAVAFX: SOFTWARE
JAVAFX: SOFTWARE DEVELOPMENT
SOFTWARE DEVELOPMENT
DEVELOPMENT stylIng
stylIng
WITH
WITH JAVAFX: SOFTWARE DEVELOPMENT stylIng
stylIng

inherit,
inherit, where
where the
the value
value is
is inherited
inherited from
from the
the parent’s
parent’s node,
node, for
for example
example
inherit,
inherit, where
where the
the value
value is
is inherited
inherited from
from the
the parent’s
parent’s node,
node, for
for example
example
inherit, where the value is inherited from the parent’s node, for example
-fx-border-color: inherit;
-fx-border-color: inherit;
-fx-border-color: inherit;
-fx-border-color: inherit;
-fx-border-color: inherit;
-fx-border-color: inherit;
-fx-border-color: inherit;
boolean, where
boolean, where the
the value
value can
can be
be true
true or
or false,
false, for
for example
example
boolean,
boolean, where
where the
the value
value can
can be
be true
true or
or false,
false, for
for example
example
boolean, where the value can be true or false, for example
-fx-display-caret: true;
-fx-display-caret: true;
-fx-display-caret: true;
-fx-display-caret: true;
-fx-display-caret: true;
-fx-display-caret: true;
-fx-display-caret: true;
string, where
string, where you
you enter
enter the
the value
value in
in quotation
quotation marks,
marks, for
for example
example
string,
string, where
where you
you enter
enter the
the value
value in
in quotation
quotation marks,
marks, for
for example
example
string, where you enter the value in quotation marks, for example
-fx-font: normal bold 24px 'areal';
-fx-font: normal bold 24px 'areal';
-fx-font: normal bold 24px 'areal';
-fx-font: normal bold 24px 'areal';
-fx-font: normal bold 24px 'areal';
-fx-font: normal bold 24px 'areal';
-fx-font: normal bold 24px 'areal';
number,
number, where
where you
you enter
enter the
the value
value as
as aa decimal
decimal number,
number, for
for example
example
number, where
number, where
number, you
where you enter
you enter the
enter the value
the value as
as aaa decimal
value as decimal number,
decimal number, for
number, for example
for example
example
-fx-border-width: 3.5;
-fx-border-width: 3.5;
-fx-border-width: 3.5;
-fx-border-width: 3.5;
-fx-border-width: 3.5;
-fx-border-width: 3.5;
-fx-border-width: 3.5;
You
You can
can also
also specify
specify aa unit
unit such
such as
as px
px (pixels),
(pixels), mm
mm (millimeters),
(millimeters), cm
cm (centimeters),
(centimeters), in
in (inches),
(inches),
You
You
You can
can
can also
also
also specify
specify
specify aa
a unit
unit
unit such
such
such as
as
as px
px
px (pixels),
(pixels),
(pixels), mm
mm
mm (millimeters),
(millimeters),
(millimeters), cm
cm
cm (centimeters),
(centimeters),
(centimeters), in
in
in (inches),
(inches),
(inches),
pt
pt (points),
(points), pc
pc (picas)
(picas) or
or em.
em. You
You can
can also
also specify
specify a
a percent
percent value.
value. Examples
Examples could
could be:
be:
pt
pt (points),
(points), pc
pc (picas)
(picas) or
or em.
em. You
You can
can also
also specify
specify aa percent
percent value.
value. Examples
Examples could
could be:
be:
pt (points), pc (picas) or em. You can also specify a percent value. Examples could be:
-fx-font-size: 18px;
-fx-font-size: 18px;
-fx-font-size: 18px;
-fx-font-size: 18px;
-fx-font-size: 18px;
-fx-font-size: 24pt;
-fx-font-size: 18px;
-fx-font-size: 18px;
-fx-font-size: 24pt;
-fx-font-size: 24pt;
-fx-font-size: 24pt;
-fx-font-size: 24pt;
-fx-border-width: 10%;
-fx-font-size: 24pt;
-fx-font-size: 24pt;
-fx-border-width: 10%;
-fx-border-width: 10%;
-fx-border-width: 10%;
-fx-border-width: 10%;
-fx-border-width: 10%;
-fx-border-width: 10%;
angle, which
angle, which is
is specified
specified by
by aa number
number and
and aa unit
unit that
that must
must be
be deg
deg (degrees)
(degrees) or
or rad
rad (radians)
(radians)
angle,
angle, which
which is
is specified
specified by
by aa number
number and
and aa unit
unit that
that must
must be
be deg
deg (degrees)
(degrees) or
or rad
rad (radians)
(radians)
angle,
for
for which
example
example is specified by a number and a unit that must be deg (degrees) or rad (radians)
for
for example
example
-fx-rotate: 45deg;
-fx-rotate: 45deg;
-fx-rotate: 45deg;
-fx-rotate: 45deg;
-fx-rotate: 45deg;
-fx-rotate: 45deg;
-fx-rotate: 45deg;
point, which
point, which is
is specified
specified using
using xx and
and yy coordinates
coordinates as
as two
two numbers
numbers separated
separated by
by whitespaces,
whitespaces,
point,
point, which
which is
is specified
specified using
using xx and
and yy coordinates
coordinates as
as two
two numbers
numbers separated
separated by
by whitespaces,
whitespaces,
point, which is specified using x and y coordinates as two numbers separated by whitespaces,
for example
for example
for example
for example
example
for
-fx-background-color: linear-gradient(from 0 0 to 100 0, repeat, red, blue);
-fx-background-color: linear-gradient(from 0 0 to 100 0, repeat, red, blue);
-fx-background-color: linear-gradient(from 0 0 to 100 0, repeat, red, blue);
-fx-background-color: linear-gradient(from 0 0 to 100 0, repeat, red, blue);
-fx-background-color: linear-gradient(from 0 0 to 100 0, repeat, red, blue);
-fx-background-color: linear-gradient(from 0 0 to 100 0, repeat, red, blue);
-fx-background-color: linear-gradient(from 0 0 to 100 0, repeat, red, blue);
There are
There are several
several other
other values
values that
that you
you can
can specify
specify for
for properties,
properties, and
and you
you should
should examine
examine
There
There
There are
are
are several
several
several other
other
other values
values
values that
that
that you
you
you can
can
can specify
specify
specify for
for
for properties,
properties,
properties, and
and
and you
you
you should
should
should examine
examine
examine
There
the
the are several
documentation
documentation other
for
for values
a
a that
complete
complete you can specify
overview,
overview, for
for for
example
example properties, and you should examine
the
the documentation
documentation for for aa complete
complete overview,
overview, for
for example
example
https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html
https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html
https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html
https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html
https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html
https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html
https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html
Above
Above is
is shown
shown aa style sheet with three styles and it must be somewhere. The project
Above
Above is
is shown
shown aa style
style
style
sheet
sheet
sheet
with
with
with
three
three
three
styles
styles
styles
and
and
and
it
it
it
must
must
must
be
be
be
somewhere.
somewhere.
somewhere.
The
The
The
project
project
project
Above is shown
StyleProgram
StyleProgram a
consists
consistsstyle
of
of sheet
the
the with
following
followingthree
files:
files: styles and it must be somewhere. The project
StyleProgram consists
StyleProgram consists of
consists of the
of the following
the following files:
following files:
files:
StyleProgram

133
131
131
131
131
131
131
131
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT Styling
stylIng

and
and the the style
style sheet
sheet in
in question
question isis thus
thus located
located inin the
the folder
folder css
css under
under resources
resources (that
(that again
again
isis located
located under
under the
the src
src directory).
directory). ItIt isis not
not aa requirement,
requirement, but but can
can be
be recommended
recommended as as
the
the file
file becomes
becomes part
part of
of the
the project’s
project’s jar
jar file.
file. Then
Then there
there isis the
the code
code for
for the
the above
above program:
program:

package styleprogram;

import javafx.application.Application;
import javafx.event.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.geometry.*;

This e-book
is made with SETASIGN
SetaPDF

PDF components for PHP developers

www.setasign.com

134
132
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX:
WITH 14: DEVELOPMENT
SOFTWAREOF APPLICATIONS
DEVELOPMENT Styling
WITH JAVAFX: SOFTWARE DEVELOPMENT stylIng

public class StyleProgram extends Application


{
private TextField txtName;
private TextField txtJob;

@Override
public void start(Stage stage)
{
HBox commands = new HBox(10,
createButton("Save", e -> { (new Alert(Alert.AlertType.INFORMATION,
"Object saved…", ButtonType.CLOSE)).show(); }),
createButton("Clear", e -> { txtName.clear(); txtJob.clear(); }));
commands.setAlignment(Pos.CENTER_RIGHT);
GridPane root = new GridPane();
root.addRow(0, createLabel(
"Name", "-fx-font-size: 18; -fx-text-fill: darkred"),
txtName = createField(300));
root.addRow(1, createLabel(
"Job", "-fx-font-size: 18; -fx-text-fill: darkgreen"),
txtJob = createField(300));
root.add(commands, 1, 2);
root.setHgap(10);
root.setVgap(20);
root.setPadding(new Insets(20, 20, 20, 20));
root.getStyleClass().add("border");
Scene scene = new Scene(root);
scene.getStylesheets().add("resources/css/styles.css");
stage.setTitle("StyleProgram");
stage.setScene(scene);
stage.show();
}

private Label createLabel(String text, String style)


{
Label label = new Label(text);
label.setStyle(style);
return label;
}

private TextField createField(double width)


{
TextField field = new TextField();
field.setPrefWidth(width);
return field;
}

135
133
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
JAVA
WITH 14: DEVELOPMENT
DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
OF APPLICATIONS
APPLICATIONS Styling
JAVA JAVAFX:
WITH
WITH 14: DEVELOPMENT
JAVAFX: SOFTWARE
SOFTWAREOF APPLICATIONS
DEVELOPMENT
DEVELOPMENT stylIng
stylIng
WITH JAVAFX: SOFTWARE DEVELOPMENT stylIng

private
private Button
Button createButton(String
createButton(String text,
text, EventHandler<ActionEvent>
EventHandler<ActionEvent> handler)
handler)
private
{ Button createButton(String text, EventHandler<ActionEvent> handler)
{
{Button cmd = new Button(text);
Button cmd = new Button(text);
Button cmd = new Button(text);
cmd.setOnAction(handler);
cmd.setOnAction(handler);
cmd.setOnAction(handler);
return
return cmd;
cmd;
} return cmd;
}
}

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

It’s a simple program where the components are laid out using a GridPane. A style sheet can
It’s a simple program where the components are laid out using a GridPane. A style sheet can
be assigned to a scene graph or a branch node. In this case, it is assigned to the scene graph:
be assigned to a scene graph or a branch node. In this case, it is assigned to the scene graph:
scene.getStylesheets().add("resources/css/styles.css");
scene.getStylesheets().add("resources/css/styles.css");
scene.getStylesheets().add("resources/css/styles.css");

Here is used a relative path to the style sheet, but you can of course also specify an absolute
Here
Here isis used
used aa relative
relative path
path to
to the
the style
style sheet,
sheet, but
but you
you can
can of
of course
course also
also specify
specify an
an absolute
absolute
path. As a result, all of the program’s TextField and Button nodes (unless stated otherwise)
path.
path. AsAs aa result,
result, all
all of
of the
the program’s
program’s TextField
TextField and
and Button
Button nodes
nodes (unless
(unless stated
stated otherwise)
otherwise)
will apply the styles defined in the style sheet. The statement
will
will apply
apply the
the styles
styles defined
defined inin the
the style
style sheet.
sheet. The
The statement
statement
root.getStyleClass().add("border");
root.getStyleClass().add("border");
root.getStyleClass().add("border");

says that the GridPane node should apply a style with the selector border, and the result is
says that the GridPane node should apply a style with the selector border, and the result is
says
that that the GridPane
the gray node should apply a style with the selector border, and the result is
frame appears.
that the gray frame appears.
that the gray frame appears.
Styles can also be defined inline, as is the case with the two Label controls. It certainly has
Styles can also be defined inline, as is the case with the two Label controls. It certainly has
Styles canbut
its uses, alsoit be
is defined
generallyinline, as is to
advisable thedefine
case with theintwo
styles Labelsheet,
a style controls. It certainly
as inline has
styles can
its uses, but it is generally advisable to define styles in a style sheet, as inline styles can
its
onlyuses, but it is ingenerally
be changed the code.advisable to define styles in a style sheet, as inline styles can
only be changed in the code.
only be changed in the code.
If you in an application considers an attribute, its value can be determined in several places,
If you in an application considers an attribute, its value can be determined in several places,
If
and you
theinfollowing
an application considerswhich
list indicates an attribute, itsthe
value has value can bepriority:
highest determined in several places,
and the following list indicates which value has the highest priority:
and the following list indicates which value has the highest priority:
1. inline (the highest priority)
1. inline (the highest priority)
1.
2. inline
parent(thenodehighest priority)
2. parent node
2.
3. parent node
scene graph
3. scene graph
3.
4. scene
valuesgraph
assigned in the code (Java properties)
4. values assigned in the code (Java properties)
4.
5. values
defaultassigned in the code (Java properties)
style sheet
5. default style sheet
5. default style sheet

136
134
134
134
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT Styling

Here you should especially note that styles have higher priority than values assigned in the
usual way in the Java code. Also note the last option with the lowest priority. If you do not
specify something, the value of a property is determined by a default style sheet.

EXERCISE 37
You must write an application that opens the following login window:

where there are 2 Label controls, 1 TextField control, 1 PasswordField control and 2 Button
controls. For these controls, the following properties must be set:

1. Label: Must have a bold Arial font on 18 points


2. TextField: Must have a bold Arial font on 14 points and the text should be dark blue
3. PasswordField: Must have a gray background and a blue frame
4. Button: Must have a blue background and a white text with a bold Arial font on
14 points

These values must all be assigned using styles defined in a style sheet.

137
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT FXML

9 FXML
FXML is an XML language that can be used to define the user interface in a JavaFX program
and thus it is an alternative to writing the code in Java. With FXML you can define the
entire scene graph or just a part of it. If in NetBeans you select JavaFX and JavaFX FXML
Application for New Project

Free eBook on
Learning & Development
By the Chief Learning Officer of McKinsey

Download Now

138
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT FXML
fXml

and
and when
when you
you click
click Next,
Next, you
you must
must enter
enter aa project
project name
name where
where II have
have typed
typed HelloFXML,
HelloFXML,
and
and when
when you
you click
click Finish,
Finish, NetBeans
NetBeans creates
creates aa project
project with
with three
three files:
files:

and
and again
again itit isis aa fully
fully finished
finished program
program that
that can
can be
be translated
translated and
and executed:
executed:

IfIf you
you click
click on
on the
the button,
button, you
you get
get aa window
window where
where aa label
label isis updated:
updated:

Then
Then there
there isis the
the code
code and
and II want
want to
to start
start with
with HelloFXML.java:
HelloFXML.java:

package hellofxml;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

137
139
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA
JAVA
WITH 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT FXML
fXml
WITH JAVAFX: SOFTWARE DEVELOPMENT
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml
fXml

public
public class HelloFXML extends Application
public class
class HelloFXML
HelloFXML extends
extends Application
Application
{
{
{
@Override
@Override
@Override
public
public void start(Stage stage) throws Exception
public void
void start(Stage
start(Stage stage)
stage) throws
throws Exception
Exception
{
{
{
Parent
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Parent root
root == FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene
Scene scene = new Scene(root);
Scene scene = new
scene = new Scene(root);
Scene(root);
stage.setScene(scene);
stage.setScene(scene);
stage.setScene(scene);
stage.show();
stage.show();
stage.show();
}
}
}

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

Immediately,
Immediately,
Immediately, itit isis aa usual
usual JavaFX
JavaFX application
application with
with aaa method
method start(),
start(), and
and there
there isis only
only one
one
Immediately, itit isis aa usual
usual JavaFX
JavaFX application
application with
with a method
method start(),
start(), and
and there
there is
is only
only one
one
difference,
difference,
difference, which
which
which isis
is the
the
the statement
statement
statement
difference, which is the statement
Parent
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Parent root
root =
= FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

which
which loads
loads the
the file
file FXMLDocument.fxml.
FXMLDocument.fxml. It isis the XML document that defines the user
which
which loads
loads the
the file FXMLDocument.fxml. ItIt
file FXMLDocument.fxml. It is the
is the XML
the XML document
XML document that
document that defines
that defines the
defines the user
the user
user
interface
interface and
and hence
hence the
the program’s
program’s sceen
sceen graph.
graph. When
When you
you see
see the
the content,
content, it’s
it’s almost
almost a
interface
interface and
and hence
hence thethe program’s
program’s sceen
sceen graph.
graph. WhenWhen you
you see
see the
the content,
content, it’s almost aaa
it’s almost
common
common
common XML
XML document:
document:
common XML XML document:
document:
<?xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0"
version="1.0" encoding="UTF-8"?>
encoding="UTF-8"?>

<?import
<?import java.lang.*?>
java.lang.*?>
<?import java.lang.*?>
<?import
<?import java.util.*?>
java.util.*?>
<?import java.util.*?>
<?import
<?import javafx.scene.*?>
javafx.scene.*?>
<?import javafx.scene.*?>
<?import
<?import javafx.scene.control.*?>
javafx.scene.control.*?>
<?import javafx.scene.control.*?>
<?import
<?import javafx.scene.layout.*?>
javafx.scene.layout.*?>
<?import javafx.scene.layout.*?>

<AnchorPane
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320"
<AnchorPane id="AnchorPane"
id="AnchorPane" prefHeight="200"
prefHeight="200" prefWidth="320"
prefWidth="320"
xmlns:fx="http://javafx.com/fxml/1"
xmlns:fx="http://javafx.com/fxml/1"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="hellofxml.FXMLDocumentController">
fx:controller="hellofxml.FXMLDocumentController">
fx:controller="hellofxml.FXMLDocumentController">
<children>
<children>
<children>
<Button
<Button layoutX="126" layoutY="90" text="Click Me!"
<Button layoutX="126"
layoutX="126" layoutY="90"
layoutY="90" text="Click
text="Click Me!"
Me!"

onAction="#handleButtonAction" fx:id="button" />
onAction="#handleButtonAction" fx:id="button" />
onAction="#handleButtonAction" fx:id="button" />
<Label
<Label layoutX="126" layoutY="120" minHeight="16" minWidth="69"
<Label layoutX="126"
layoutX="126" layoutY="120"
layoutY="120" minHeight="16"
minHeight="16" minWidth="69"
minWidth="69"

fx:id="label" />
fx:id="label" />
fx:id="label" />
</children>
</children>
</children>
</AnchorPane>
</AnchorPane>
</AnchorPane>

140
138
138
138
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT FXML
fXml

The
The document
document starts
starts with
with some
some import
import directives,
directives, which
which youyou can
can easily
easily interpret.
interpret. Otherwise,
Otherwise,
the
the document
document consists
consists ofof elements
elements that
that corresponds
corresponds to to classes
classes for
for nodes
nodes in in the
the scene
scene graph,
graph,
and
and even
even the
the same
same names
names apply.
apply. For
For the
the individual
individual elements,
elements, youyou can can define
define attributes
attributes that
that
match
match thethe properties
properties of of the
the corresponding
corresponding node node classes,
classes, and
and here
here thethe same
same names
names apply.
apply.
The
The only
only exception
exception isis the
the attribute
attribute fx:id,
fx:id, which
which refers
refers to
to aa variable
variable defined
defined inin the
the controller
controller
class.
class. In
In addition,
addition, note
note the
the value
value of
of the
the attribute
attribute onAction
onAction forfor the
the Button
Button item,
item, which
which refers
refers
to
to aa method
method (an(an event
event handler)
handler) inin the
the controller
controller class.
class. The
The class
class isis as
as follows:
follows:

package hellofxml;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;

public class FXMLDocumentController implements Initializable


{
@FXML
private Label label;

www.sylvania.com

We do not reinvent
the wheel we reinvent
light.
Fascinating lighting offers an infinite spectrum of
possibilities: Innovative technologies and new
markets provide both opportunities and challenges.
An environment in which your expertise is in high
demand. Enjoy the supportive working atmosphere
within our global group and benefit from international
career paths. Implement sustainable ideas in close
cooperation with other specialists and contribute to
influencing our future. Come and join us in reinventing
light every day.

Light is OSRAM

141
139
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX: SOFTWARE
14: DEVELOPMENT OFDEVELOPMENT
APPLICATIONS FXML
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

@FXML
@FXML
private
private void
void handleButtonAction(ActionEvent event)
handleButtonAction(ActionEvent event)
{
{
System.out.println("You clicked me!");
System.out.println("You clicked me!");
label.setText("Hello World!");
label.setText("Hello World!");
}
}

@Override
@Override
public
public void
void initialize(URL url, ResourceBundle
initialize(URL url, ResourceBundle rb)
rb)
{
{
}
}
}
}

The
The class
class defines
defines a variable and two methods. The first is a reference
reference to
to the
the control
control defined
defined
in
in the
the XML
XML section, and here
section, and here you
you should
should note
note the
the annotation
annotation @FXML.
@FXML. ItIt means
means that
that an an
FXMLLoader
FXMLLoader can create an object defined in in FXML
FXML by by injection.
injection. The
The same
same notation
notation isis used
used
for
for the
the event which means
event handler for the button, which means itit can
can be
be referenced
referenced from
from the
the FXML
FXML
section.
section. You
You should note that the class implements the interface
interface Initializable,
Initializable, which
which defines
defines
a single method that can be used to initialize
initialize the
the controller.
controller.

The
The above
above is created, and
is what NetBeans has automatically created, and II will
will now
now have
have to
to make
make changes
changes
to
to FXMLDocument.fxml
FXMLDocument.fxml and FXMLDocumentController.java.
FXMLDocumentController.java. The The class
class HelloFXML.java
HelloFXML.java will
will
be
be unchanged.
unchanged. FXMLDocument.fxml has beenbeen changed
changed to:
to:

<?xml version="1.0" encoding="UTF-8"?>


encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.text.*?>

<VBox alignment="CENTER" spacing="20"


spacing="20" prefWidth="400"
prefWidth="400"
xmlns:fx="http://javafx.com/fxml/1"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="hellofxml.FXMLDocumentController">
fx:controller="hellofxml.FXMLDocumentController">
<style>
-fx-padding: 20;
-fx-border-style: solid;
-fx-border-width: 2;
-fx-border-insets: 25;
-fx-border-radius: 10;
-fx-border-color: darkred;
-fx-border-color: darkred;
</style>
</style>
<children>
<children>
<TextField fx:id="name" prefWidth="300" maxWidth="300" />
<TextField fx:id="name" prefWidth="300" maxWidth="300" />

142
140
140
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA
WITH 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT FXML
fXml
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

<Button text="Click Me!" prefWidth="100" onAction="#handleButtonAction"


<Button text="Click Me!" prefWidth="100" onAction="#handleButtonAction"
fx:id="button" />
fx:id="button" />
<Label minHeight="20" fx:id="label" textFill="red" >
<Label minHeight="20" fx:id="label" textFill="red" >
<font>
<font>
<Font name="Aria" size="24.0" />
<Font name="Aria" size="24.0" />
</font>
</font>
</Label>
</Label>
</children>
</children>
</VBox>
</VBox>

Two new
Two new import
new import directives
import directives have
directives have been
have been added,
been added, and
added, and the
and the AnchorPane
the AnchorPane element
AnchorPane element has
element has been
has been replaced
been replaced
replaced
Two
by aaa VBox
by VBox element.
VBox element. Then
element. Then aaa style
Then style element
style element and
element and aaa TextField
and TextField element
TextField element are
element are added,
are added, and
added, and many
and many
many
by
attributes are
attributes are also
are also changed.
also changed. When
changed. When you
When you see
you see the
see the code,
the code, it
code, itit is
isis easy
easy enough
easy enough to
enough to understand
to understand ––– at
understand at
at
attributes
least if
least ifif you
you know
you know JavaFX.
know JavaFX. As
JavaFX. As aaa result,
As result, the
result, the window
the window changes
window changes to
changes to the
to the following:
the following:
following:
least

where the
where the text
the text Carlo
text Carlo is
Carlo isis entered
entered in
entered in the
in the entry
the entry field
entry field and
field and then
and then clicked
then clicked on
clicked on the
on the button.
the button. In
button. In the
In the
the
where
controller, nothing
controller, nothing else
nothing else has
else has been
has been added
been added than
added than an
than an additional
an additional variable
additional variable has
variable has been
has been added
been added and
added and the
and the
the
controller,
event handler
event handler has
handler has been
has been changed:
been changed:
changed:
event

package hellofxml;
package hellofxml;
import java.net.URL;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextField;

public class FXMLDocumentController implements Initializable


public class FXMLDocumentController implements Initializable
{
{
@FXML
@FXML
private Label label;
private Label label;
@FXML
@FXML
private TextField name;
private TextField name;

@FXML
@FXML
private void handleButtonAction(ActionEvent event)
private void handleButtonAction(ActionEvent event)

143
141
141
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA 14:
WITH DEVELOPMENT OFDEVELOPMENT
APPLICATIONS
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT FXML
fXml
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

{
{
label.setText("Hello: " + name.getText());
label.setText("Hello: " + name.getText());
name.setText("");
name.setText("");
}
}

@Override
@Override
public void initialize(URL url, ResourceBundle rb)
public void initialize(URL url, ResourceBundle rb)
{
{
}
}
}
}

9.1
9.1 CREATE
9.1 CREATE OBJECTS
CREATE OBJECTS
OBJECTS
As
As illustrated
As illustrated in
illustrated in the
in the previous
the previous example,
previous example, FXML
example, FXML is
FXML is used
is used to
used to define
to define aaa program’s
define program’s scene
program’s scene graph
scene graph or
graph or
or
part
part of
of the
the graph,
graph, but
but FXML
FXML may
may more
more generally
generally be
be
360°
used
used to
to define
define
part of the graph, but FXML may more generally be used to define an object graph. In an
an object
object graph.
graph. In
In

.
this
this section,
this section, III will
section, will show
will show aaa program
show program called
program called ObjectsFXML,
called ObjectsFXML, which
ObjectsFXML, which will
which will show
will show you
show you how
you how to
how to create
to create
create

thinking
objects
objects using FXML. The ObjectsFXML.java program class does not contain anything new
objects using
using FXML.
FXML. The
The ObjectsFXML.java
ObjectsFXML.java program
program class
class does
does not
not contain
contain anything
anything new
new
and
and will
will not
not be
be shown
shown here.
here. The
The file
file FXMLDocument.fxml
FXMLDocument.fxml has
has the
the following
and will not be shown here. The file FXMLDocument.fxml has the following content:following content:
content:

<?xml version="1.0" encoding="UTF-8"?>


<?xml version="1.0" encoding="UTF-8"?>

360°
thinking . 360°
thinking .
Discover the truth at www.deloitte.ca/careers Dis

© Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers © Deloitte & Touche LLP and affiliated entities.

Deloitte & Touche LLP and affiliated entities.

Discover the truth at www.deloitte.ca/careers


144
142
142
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA JAVAFX:
WITH
WITH 14: DEVELOPMENT
JAVAFX: SOFTWAREOF
SOFTWARE APPLICATIONS
DEVELOPMENT
DEVELOPMENT FXML
fXml
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

<?import java.lang.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.text.*?>
<?import javafx.geometry.*?>
<?import javafx.geometry.*?>
<?import java.lang.*?>
<?import java.lang.*?>
<?import javafx.collections.*?>
<?import javafx.collections.*?>
<?import objectsfxml.*?>
<?import objectsfxml.*?>

<VBox prefHeight="200" prefWidth="320" spacing="20" alignment="CENTER"


<VBox prefHeight="200" prefWidth="320" spacing="20" alignment="CENTER"
xmlns:fx="http://javafx.com/fxml/1"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="objectsfxml.FXMLDocumentController">
fx:controller="objectsfxml.FXMLDocumentController">
<padding><Insets top="20" right="20" bottom="20" left="20"/></padding>
<padding><Insets top="20" right="20" bottom="20" left="20"/></padding>
<children>
<children>
<Text fx:id="header" />
<Text fx:id="header" />
<ComboBox fx:id="lstKings" >
<ComboBox fx:id="lstKings" >
<items>
<items>
<FXCollections fx:factory="observableArrayList">
<FXCollections fx:factory="observableArrayList">
<String fx:value="Gorm den Gamle"/>
<String fx:value="Gorm den Gamle"/>
<String fx:value="Harald Blåtand"/>
<String fx:value="Harald Blåtand"/>
<String fx:value="Svend Tveskæg"/>
<String fx:value="Svend Tveskæg"/>
<String fx:value="Harald den 2."/>
<String fx:value="Harald den 2."/>
<String fx:value="Knud den Store"/>
<String fx:value="Knud den Store"/>
</FXCollections>
</FXCollections>
</items>
</items>
</ComboBox>
</ComboBox>
<Button text="Select a king" onAction="#handleKings" fx:id="button" />
<Button text="Select a king" onAction="#handleKings" fx:id="button" />
<ComboBox fx:id="lstPersons" />
<ComboBox fx:id="lstPersons" />
<Button text="Select a king" onAction="#handlePersons" />
<Button text="Select a king" onAction="#handlePersons" />
<Label fx:id="label" >
<Label fx:id="label" >
<String fx:value="A unknown Person" />
<String fx:value="A unknown Person" />
</Label>
</Label>
</children>
</children>
</VBox>
</VBox>

For example,
For example, ifif you
you look
look at
at the
the item
item
For example, if you look at the item
<VBox prefHeight="200" …
<VBox prefHeight="200" …

this means
this means that
that an
an object
object of
of the
the type
type VBox
VBox isis being
being instantiated.
instantiated. First
First of
of all,
all, itit requires
requires an
an
this means that an object of the type VBox is being instantiated. First of all, it requires an
import directive
import directive for
for the
the package
package containing
containing the
the class
class VBox,
VBox, and
and that
that the
the class
class hashas aa default
default
import directive for the package containing the class VBox, and that the class has a default
constructor, as
constructor, as the
the syntax
syntax does
does not
not contain
contain any
any immediate
immediate way
way toto transfer
transfer values
values to to the
the
constructor, as the syntax does not contain any immediate way to transfer values to the
constructor. Similarly,
constructor. Similarly, the
the element
element
constructor. Similarly, the element
<Text fx:id="header" />
<Text fx:id="header" />

145
143
143
JAVA
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT FXML
fXml
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

means
means that
that aa Text
Text object
object isis created
created and
and that
that itit isis referred
referred toto in
in the
the controller
controller ofof the
the variable
variable
header.
header. Here,
Here, the
the object
object isis also
also assigned
assigned aa value
value thatthat II return
return toto below.
below. The The next
next thing
thing that
that
happens
happens is to create a ComboBox called lstKings (the name that the corresponding object isis
is to create a ComboBox called lstKings (the name that the corresponding object
called
called in
in the
the controller).
controller). InIn particular,
particular, note
note how
how the the ComboBox
ComboBox isis initialized.
initialized. This
This happens
happens
with
with anan ObservableList,
ObservableList, and
and herehere the
the syntax
syntax means
means that that the
the list
list isis created
created using
using aa factory
factory
method,
method, explained
explained below.
below. The
The individual
individual items
items in in the
the list
list are
are of
of the
the type
type String
String and
and the
the item
item

<String fx:value="Gorm den Gamle"/>


<String fx:value="Gorm den Gamle"/>

creates aa String
creates String object
object by
by performing
performing aa static
static method
method valueOf()
valueOf() initialized
initialized with
with the
the current
current
value. It
value. It requires
requires that
that the
the class
class of
of which
which to to instantiate
instantiate an
an object
object has
has such
such aa method
method and
and itit
has the
has the class
class String.
String. The
The result
result of
of all
all isis that
that aa ComboBox
ComboBox isis created
created with
with 55 String
String objects.
objects.

As aa next
As next step,
step, aa button
button isis created
created where
where there
there isis nothing
nothing new
new to
to explain,
explain, and
and then
then an
an empty
empty
ComboBox called
ComboBox called lstPersons
lstPersons and
and finally
finally another
another button.
button. Finally,
Finally, aa Label
Label isis created,
created, and
and here
here
you will
you will notice
notice howhow this
this Label
Label isis initialized
initialized with
with aa String
String object.
object. IfIf you
you runrun the
the program,
program,
you get
you get the
the following
following window:
window:

where aa name
where name isis selected
selected inin the
the top
top combobox
combobox and and then
then clicked
clicked on
on the
the top
top button.
button. The
The
other ComboBox
other ComboBox isis also
also initialized,
initialized, and
and itit isis done
done using
using aa factory,
factory, as
as shown
shown below.
below. The
The
ComboBox isis initialized
ComboBox initialized with
with Objects
Objects of
of the
the type:
type:

package
package objectsfxml;
objectsfxml;

public class
public class Person
Person
{
{
private String
private String name;
name;
private
private String job;
String job;

146
144
144
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH14: DEVELOPMENT
JAVAFX: OF DEVELOPMENT
SOFTWARE APPLICATIONS FXML
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

public Person(String name, String job)


{
this.name = name;
this.job = job;
}

public String getName()


{
return name;
}

public void setName(String name)


{
this.name = name;
}

public String getJob()


{
return job;
}

We will turn your CV into


an opportunity of a lifetime

Do you like cars? Would you like to be a part of a successful brand? Send us your CV on
We will appreciate and reward both your enthusiasm and talent. www.employerforlife.com
Send us your CV. You will be surprised where it can take you.

147
145
JAVA 14:
JAVA 14: DEVELOPMENT OF
OF APPLICATIONS
JAVA 14: DEVELOPMENT
DEVELOPMENT OF APPLICATIONS
APPLICATIONS
JAVA
WITH
JAVA 14:
14: DEVELOPMENT
JAVAFX: OF
SOFTWARE
DEVELOPMENT APPLICATIONS
DEVELOPMENT
OFDEVELOPMENT
APPLICATIONS fXml
WITH JAVAFX: SOFTWARE
WITH JAVAFX: SOFTWARE DEVELOPMENT FXML
fXml
WITH JAVAFX: SOFTWARE DEVELOPMENT
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml
fXml

public void setJob(String job)


public
public void
void setJob(String
setJob(String job)
public
{ void setJob(String job)
job)
{
{
{this.job = job;
this.job = job;
}this.job
this.job =
= job;
job;
}
}
}
@Override
@Override
@Override
@Override
public String toString()
public
public String toString()
public String
{ String toString()
toString()
{
{
{return String.format("%s, %s", name, job);
return String.format("%s, %s", name, job);
}return
return String.format("%s,
String.format("%s, %s",
%s", name,
name, job);
job);
}
}
}}
}
}
}

which
which is
is aa simple
simple model
model class
class that
that II have
have previously
previously shown.
shown. Note
Note that
that the
the class
class has
has no
no default
default
which
which
which is
is aa simple
simple
is a simple model
model
model class
class that
that
class that II have
have previously
previously
I have previously shown.
shown.
shown. Note
Note
Note that
that the
the
that the class
class has
has no
no default
no default
class hasparameters
default
constructor,
constructor, and
and if
if you
you want
want to
to instantiate
instantiate an
an object,
object, it
it is
is necessary
necessary to
to transfer
transfer parameters
constructor,
constructor,
constructor, and
and if
if you
you
and if you want
want
wantyouto
to instantiate
instantiate
to instantiate an
an object,
object,
anthat
object, it
it is
is necessary
necessary
it is necessary to
to transfer
transfer
toclass
transfer parameters
parameters
parameters
to
to the
the constructor.
constructor. Because
Because you not
not can
can do
do that in
in FXML,
FXML, aa builder
builder class is
is used,
used, that
that is
toto
to the
the
the constructor.
constructor.
constructor. Because
Because
Because you
you
you not
not
not can
can
can do
do
do that
that
that in
in
in FXML,
FXML,
FXML, aa
a builder
builder
builder class
class
class is
is
is used,
used,
used, that
that
that isis
is
is
aa class
class that
that implements
implements an
an interface:
interface:
aaa class that
class that
class implements
that implements an
implements an interface:
an interface:
interface:
public interface Builder<T>
public
public interface Builder<T>
public interface
{ interface Builder<T>
Builder<T>
{
{
{public T build();
public T build();
}public
public T
T build();
build();
}
}
}

and
and
and aaaa class
class
class that
that
that implements
implements
implements this
this
this interface
interface
interface how
how
how to
to
to instantiate
instantiate
instantiate objects
objects
objects of
of
of the
the
the type
type
type T.
T.
T. The
The
The class
class
class
and
and a class
class that
that implements
implements this
this interface
interface how
how to
to instantiate
instantiate objects
objects of
of the
the type
type T.
T. The
The class
class
is
isis used
used
used by
by
by a
a
a factory
factory
factory class
class
class that
that
that implements
implements
implements another
another
another interface:
interface:
interface:
is used
is used by by aa factory
factory class
class that
that implements
implements another
another interface:
interface:
public interface BuilderFactory
public
public interface BuilderFactory
public interface
{ interface BuilderFactory
BuilderFactory
{
{
{public Builder<?> getBuilder(Class<?> type);
public Builder<?> getBuilder(Class<?> type);
}public
public Builder<?>
Builder<?> getBuilder(Class<?>
getBuilder(Class<?> type);
type);
}
}
}

The
The
The FXMLLoader
FXMLLoader
FXMLLoader class
class
class uses
uses
uses aaa BuilderFactory
BuilderFactory ifif itit can
can not
not create
create an
an object
object otherwise,
otherwise, and
and
The
The FXMLLoader
FXMLLoader class
class uses
uses aa BuilderFactory
BuilderFactory
BuilderFactory
if
if
if
it
it
it
can
can
can
not
not
not
create
create
create
an
an
an
object
object
object
otherwise,
otherwise,
otherwise,
and
and
and
itit
it happens
happens
happens bt
bt
bt calling
calling
calling the
the
the method
method
method getBuilder()
getBuilder()
getBuilder() with
with
with the
the
the type
type
type as
as
as argument.
argument.
argument. If
If
If this
this
this method
method
method
it
it happens
happens bt
bt calling
calling the
theaa method
method getBuilder()
getBuilder() with
with the
the to type
type as
as argument.
argument. If
If this
this method
method
returns
returns
returns aaa Builder
Builder
Builder object,
object,
object, a FXMLLoader
FXMLLoader
FXMLLoader uses
uses
uses this
this
this object
object
object to
to initialize
initialize
initialize the
the
the required
required
required properties
properties
properties
returns
returns aa Builder
Builder object,
object, aa FXMLLoader
FXMLLoader uses
uses this object
thiscalled
objecttheto initialize
to method the
the required
initializebuild()required properties
properties
of
of
of the
the
the object
object
object to
to
to be
be
be instantiated
instantiated
instantiated and
and
and eventually
eventually
eventually called
called the
the method
method build()
build() that
that
that returns
returns
returns the
the
the
of
of the
the object
object to
to be
be instantiated
instantiated and
and eventually
eventually called
called the
the method
method build()
build() that
that returns
returns the
the
object.
object.
object. The
The
The builder
builder
builder class
class
class must
must
must have
have
have get
get
get and
and
and set
set
set methods
methods
methods for
for
for all
all
all the
the
the constructor’s
constructor’s
constructor’s parameters.
parameters.
parameters.
object.
object. The
The builder
builder class must
classdefine have
must aahave get and
get and set
set methods
methods for all
for as
all the constructor’s parameters.
the constructor’s parameters.
In
In
In this
this
this case,
case,
case, you
you
you must
must
must define
define a Builder
Builder
Builder for
for
for the
the
the class
class
class Person
Person
Person as
as follows:
follows:
follows:
In
In this
this case,
case, you
you must
must define
define aa Builder
Builder for
for the
the class
class Person
Person as as follows:
follows:
package objectsfxml;
package
package objectsfxml;
objectsfxml;
package objectsfxml;
import javafx.util.*;
import
import javafx.util.*;
javafx.util.*;
import javafx.util.*;
public class PersonBuilder implements Builder<Person>
public
public class PersonBuilder implements Builder<Person>
public class
{ class PersonBuilder
PersonBuilder implements
implements Builder<Person>
Builder<Person>
{
{
{private String name;
private
private String name;
private String
String name;
name;
job;
private
private String job;
private String
String job;
job;

146
148
146
146
146
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
JAVA 14:
WITH DEVELOPMENT OFDEVELOPMENT
APPLICATIONS
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT FXML
fXml
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

public String getName() {


public String getName() {
return name;
return name;
}
}

public void setName(String name) {


public void setName(String name) {
this.name = name;
this.name = name;
}
}

public String getJob() {


public String getJob() {
return job;
return job;
}
}

public void setJob(String job) {


public void setJob(String job) {
this.job = job;
this.job = job;
}
}

@Override
@Override
public Person build()
public Person build()
{
{
return new Person(name, job);
return new Person(name, job);
}
}
}
}

AA Builder
Builder is thus
thus aaa class
class that
that solve
solve the
the problem
problem that
that you
you can
can not
not construct
construct an
an object
object of
of aaa
A Builder isis thus class that solve the problem that you can not construct an object of
class
class (here
(here Person)
Person) without
without transferring
transferring parameters
parameters to
to the
the constructor.
constructor.
class (here Person) without transferring parameters to the constructor.

In
In addition
addition to
to aaa Builder,
Builder, you
you must
must have
have aaa BuilderFactory,
BuilderFactory, and
and in
in this
this case
case it can
can be
be written
itit can written
In addition to Builder, you must have BuilderFactory, and in this case be written
as
as follows:
follows:
as follows:

package objectsfxml;
package objectsfxml;

import javafx.util.*;
import javafx.util.*;
import javafx.fxml.*;
import javafx.fxml.*;

public class PersonFactory implements BuilderFactory


public class PersonFactory implements BuilderFactory
{
{
private final JavaFXBuilderFactory fxFactory = new JavaFXBuilderFactory();
private final JavaFXBuilderFactory fxFactory = new JavaFXBuilderFactory();

@Override
@Override
public Builder<?> getBuilder(Class<?> type)
public Builder<?> getBuilder(Class<?> type)
{
{
if (type == Person.class) return new PersonBuilder();
if (type == Person.class) return new PersonBuilder();
return fxFactory.getBuilder(type);
return fxFactory.getBuilder(type);
}
}
}
}

149
147
147
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT FXML
fXml

The method getBuilder() has a type as parameter, and if this type is Person, a PersonBuilder
is returned. Otherwise, a default builder will be returned for that type.

For the project ObjectsFXML, I have created a directory resources / fxml, and I have added
a file named Persons.fxml whose content are:

<?xml version="1.0" encoding="UTF-8"?>

<?import objectsfxml.*?>
<?import java.util.ArrayList?>

<ArrayList>
<Person name="Hardeknud" job="Konge"/>
<Person name="Magnus den Gode" job="Konge"/>
<Person name="Svend Estridsen" job="Konge"/>
<Person name="Harald Hen" job="Konge"/>
<Person name="Knud den Hellige" job="Konge"/>
</ArrayList>

That is, a XML document that defines 5 Person objects, but in order to instantiate these
objects, a Builder is required. It happens in the controller:

148
150
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA JAVAFX:
WITH 14: DEVELOPMENT
SOFTWAREOF APPLICATIONS
DEVELOPMENT FXML
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

public class FXMLDocumentController implements Initializable


{
@FXML
private Text header;
@FXML
private Label label;
@FXML
private ComboBox lstKings;
@FXML
private ComboBox lstPersons;

@FXML
private void handleKings(ActionEvent event)
{
label.setText("" + lstKings.getSelectionModel().getSelectedItem());
lstKings.getSelectionModel().clearSelection();
}

@FXML
private void handlePersons(ActionEvent event)
{
label.setText("" + lstPersons.getSelectionModel().getSelectedItem());
lstPersons.getSelectionModel().clearSelection();
}

@Override
public void initialize(URL url, ResourceBundle rb)
{
header.setText("Objects");
header.setFont(Font.font("Arial", FontWeight.BOLD, FontPosture.REGULAR, 24));
try
{
lstPersons.getPersons().addAll(
FXCollections.observableArrayList(loadItems(new PersonFactory())));
}
catch (Exception ex)
{
System.out.println(ex);
}
}

public ArrayList loadPersons(BuilderFactory builderFactory) throws Exception


{
URL url = FXMLDocumentController.class.getClassLoader().getResource(
"resources/fxml/Persons.fxml");
FXMLLoader loader = new FXMLLoader();
loader.setLocation(url);

151
149
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
JAVA 14:
WITH 14: DEVELOPMENT
DEVELOPMENT
JAVAFX: SOFTWAREOF APPLICATIONS
OFDEVELOPMENT
APPLICATIONS FXML
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT fXml
fXml

loader.setBuilderFactory(builderFactory);
loader.setBuilderFactory(builderFactory);
return
return loader.<ArrayList>load();
}}
}}

Note
Note that
that atat the
the start
start of
of the
the controller, variables are
controller, variables are defined
defined corresponding
corresponding to to elements
elements
defined
defined inin the
the FXML
FXML document.
document. Next,
Next, there are the
there are the events
events of
of the
the two
two buttons
buttons that that do
do not
not
require
require any
any particular
particular explanation.
explanation. In
In the method initialize(),
the method initialize(), the
the object
object header
header isis initialized
initialized
by
by the
the loader,
loader, and
and the
the same
same applies
applies to
to lstPersons, which is
lstPersons, which is the
the bottom
bottom ComboBox.
ComboBox. This This isis
done
done by
by calling
calling the
the method
method loadPersons(), as with
loadPersons(), as with aa FXMLLoader
FXMLLoader loadsloads the
the XMLXML document
document
with
with the
the definitions
definitions of Person objects, using a BuilderFactory, that here
BuilderFactory, that here isis aa PersonFactory.
PersonFactory.

9.2 DIALOGFXML
9.2 DIALOGFXML
9.2
II will
will write
write aa program
program similar to the program DialogProgram from chapter
DialogProgram from chapter 7,7, when
when the
the
difference
difference isis that
that the user interface is written in FXML. start with
FXML. II start with aa JavaFX
JavaFX FXML
FXML
Application
Application project,
project, which I have called DialogFXML. The
The main program isis unchanged,
main program unchanged, but
but
FXMLDocument
FXMLDocument is is changed to the following:

<?xml version="1.0"
<?xml version="1.0" encoding="UTF-8"?>

<?import
<?import java.lang.*?>
java.lang.*?>
<?import
<?import java.util.*?>
java.util.*?>
<?import
<?import javafx.scene.*?>
javafx.scene.*?>
<?import
<?import javafx.scene.control.*?>
javafx.scene.control.*?>
<?import
<?import javafx.scene.layout.*?>
javafx.scene.layout.*?>

<VBox prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1"


<VBox prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="dialogfxml.FXMLDocumentController"
fx:controller="dialogfxml.FXMLDocumentController"
spacing="20" alignment="CENTER"
spacing="20" alignment="CENTER" >
>
<children>
<children>
<Button prefWidth="150" text="Enter person" onAction="#handleEnterAction" />
<Button prefWidth="150" text="Enter person" onAction="#handleEnterAction" />
<Button prefWidth="150" text="Show persons" onAction="#handleShowAction" />
<Button prefWidth="150" text="Show persons" onAction="#handleShowAction" />
</children>
</children>
</VBox>
</VBox>

152
150
150
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT FXML
fXml

which
which defines
defines aa window
window with
with two
two buttons:
buttons:

II have
have then
then added
added the
the class
class Person
Person from
from the
the project
project DialogProgram.
DialogProgram. The
The window’s
window’s controller
controller
can
can then
then be
be written
written as
as follows:
follows:

public class FXMLDocumentController implements Initializable


{
private List<Person> list = new ArrayList();

@FXML
private void handleEnterAction(ActionEvent event)
{

AXA Global
Graduate Program
Find out more and apply

153
151
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH 14: DEVELOPMENT
JAVAFX: OFDEVELOPMENT
SOFTWARE APPLICATIONS FXML
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

try
{
FXMLLoader loader =
new FXMLLoader(getClass().getResource("EnterDocument.fxml"));
Parent root = loader.load();
((EnterDocumentController)loader.getController()).setList(list);
Dialog<Person> dlg = new Dialog();
dlg.getDialogPane().setContent(root);
dlg.setTitle("Enter person");
dlg.showAndWait();
}
catch (Exception ex)
{
}
}

@FXML
private void handleShowAction(ActionEvent e)
{
try
{
FXMLLoader loader =
new FXMLLoader(getClass().getResource("ShowDocument.fxml"));
Parent root = loader.load();
((ShowDocumentController)loader.getController()).setList(list);
Dialog<Person> dlg = new Dialog();
dlg.setTitle("Persons");
dlg.setHeaderText("You have entered the following persons:");
dlg.getDialogPane().setContent(root);
dlg.showAndWait();
}
catch (Exception ex)
{
}
}

@Override
public void initialize(URL url, ResourceBundle rb)
{
}
}

First, note that a list has been defined for Person objects, but otherwise the class consists
First, note that a list has been defined for Person objects, but otherwise the class consists
primarily of the event handlers for the two buttons. In principle, the two methods work
primarily of the event handlers for the two buttons. In principle, the two methods work
in the same way as they starts to load the XML that defines the user interface, and then
in the same way as they starts to load the XML that defines the user interface, and then
the list of Person objects must be transferred to the controller for the dialog box. Here
the list of Person objects must be transferred to the controller for the dialog box. Here
you should especially note how to refer to the controller. To create a dialog box, I add an
you should especially note how to refer to the controller. To create a dialog box, I add an
Empty FMXL:
Empty FMXL:

154
152
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml
WITH JAVAFX: SOFTWARE DEVELOPMENT FXML

After
After clicking
clicking Next,
Next, II have
have to
to enter
enter the
the name
name (for
(for example,
example, ShowDocument),
ShowDocument), and
and in
in the
the next
next
window
window youyou can
can choose
choose whether
whether toto create
create aa controller:
controller:

Finally,
Finally, there
there isis aa window
window where
where you
you can
can specify
specify whether
whether there
there should
should be
be aa stylesheet,
stylesheet, and
and
then
then NetBeans
NetBeans has has added
added two
two new
new files.
files. If
If itit isis the
the dialog
dialog box
box for
for entering
entering aa person,
person, they
they
are
are called
called EnterDocument.fxml
EnterDocument.fxml and and EnterDocumentController.java.
EnterDocumentController.java. Below Below is
is the
the FXML
FXML codecode
that
that defines GridPane ::
defines aa GridPane

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.*?>

153
155
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS FXML
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

<GridPane id="GridPane" xmlns:fx="http://javafx.com/fxml/1"


fx:controller="dialogfxml.EnterDocumentController" hgap="10" vgap="20" >
<padding><Insets top="10" right="10" bottom="10" left="10"/></padding>
<Label GridPane.rowIndex="0" GridPane.columnIndex="0" >Name</Label>
<TextField fx:id="txtName" GridPane.rowIndex="0" GridPane.columnIndex="1"
prefWidth="300" ></TextField>
<Label GridPane.rowIndex="1" GridPane.columnIndex="0" >Job</Label>
<TextField fx:id="txtJob" GridPane.rowIndex="1" GridPane.columnIndex="1"
prefWidth="300" ></TextField>
<Label GridPane.rowIndex="2" GridPane.columnIndex="0" >Date</Label>
<DatePicker fx:id="ctlDate" GridPane.rowIndex="2" GridPane.columnIndex="1"
prefWidth="150" ></DatePicker>
<HBox GridPane.rowIndex="3" GridPane.columnIndex="1" alignment="CENTER_RIGHT"
spacing="10" >
<Button text="OK" onAction="#handleOkAction" />
<Button text="Cancel" onAction="#handleCancelAction" />
</HBox>
</GridPane>

Here is not much new compared to what has previously been shown, but you should note
that a DataPicker has been added, which is a node in the same way as other nodes. The
controller is as follows:

�e Graduate Programme
I joined MITAS because for Engineers and Geoscientists
I wanted real responsibili� www.discovermitas.com
Maersk.com/Mitas �e G
I joined MITAS because for Engine
I wanted real responsibili� Ma

Month 16
I was a construction Mo
supervisor ina const
I was
the North Sea super
advising and the No
Real work he
helping foremen advis
International
al opportunities
Internationa
�ree wo
work
or placements ssolve problems
Real work he
helping fo
International
Internationaal opportunities
�ree wo
work
or placements ssolve pr

156
154
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA 14:
WITH DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS FXML
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

public class EnterDocumentController implements Initializable


{
private List<Person> list;

@FXML
private TextField txtName;
@FXML
private TextField txtJob;
@FXML
private DatePicker ctlDate;

public void setList(List<Person> list)


{
this.list = list;
}

@FXML
private void handleOkAction(ActionEvent e)
{
list.add(new Person(txtName.getText(), txtJob.
getText(), ctlDate.getValue()));
((Stage)((Node) e.getSource()).getScene().getWindow()).close();
}

@FXML
private void handleCancelAction(ActionEvent e)
{
((Stage)((Node) e.getSource()).getScene().getWindow()).close();
}

@Override
public void initialize(URL url, ResourceBundle rb)
{
}
}

Also,
Also, here
here is
is not
not much
much new,
new, but
but you
you should
should note
note that
that aa method
method has
has been
been added
added as
as setList(),
setList(),
so
so there is access to the list of Person objects in the event handler for the OK button. You
there is access to the list of Person objects in the event handler for the OK button. You
should
should also
also note
note how
how to
to close
close the
the window
window byby obtaining
obtaining aa reference
reference to
to the
the Stage
Stage object
object that
that
represents
represents the window. If you run the program and click on the top button, you get the
the window. If you run the program and click on the top button, you get the
following window:
following window:

157
155
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT FXML
fXml

The
The XML
XML code
code of
of the
the other
other dialog
dialog box
box is:
is:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.*?>

<BorderPane xmlns:fx="http://javafx.com/fxml/1"
fx:controller="dialogfxml.ShowDocumentController">
<padding><Insets top="20" right="20" bottom="0" left="20"/></padding>
<center>
<ListView prefWidth="400" prefHeight="300" fx:id="lstPersons" />
</center>
<bottom>
<HBox alignment="CENTER_RIGHT" >
<padding><Insets top="20" right="0" bottom="0" left="0"/></padding>
<Button text="Close" onAction="#handleCloseAction" />
</HBox>
</bottom>
</BorderPane>

and
and isis basically
basically aa BorderPane.
BorderPane. Note
Note that
that the
the center
center isis aa ListView,
ListView, which
which isis not
not initialized
initialized
here,
here, but
but isis instead
instead done
done itit in
in the
the controller,
controller, which
which isis trivial:
trivial:

public class ShowDocumentController implements Initializable


{
@FXML
private ListView lstPersons;

156
158
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH 14: DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS FXML
WITH JAVAFX: SOFTWARE DEVELOPMENT fXml

public void setList(List<Person> list)


{
lstPersons.getItems().addAll(list);
}

@FXML
private void handleCloseAction(ActionEvent e)
{
((Stage)((Node) e.getSource()).getScene().getWindow()).close();
}

@Override
public void initialize(URL url, ResourceBundle rb)
{
}
}

93%
OF MIM STUDENTS ARE
WORKING IN THEIR SECTOR 3 MONTHS
FOLLOWING GRADUATION

MASTER IN MANAGEMENT
• STUDY IN THE CENTER OF MADRID AND TAKE ADVANTAGE OF THE UNIQUE OPPORTUNITIES
Length: 1O MONTHS
THAT THE CAPITAL OF SPAIN OFFERS
Av. Experience: 1 YEAR
• PROPEL YOUR EDUCATION BY EARNING A DOUBLE DEGREE THAT BEST SUITS YOUR
Language: ENGLISH / SPANISH
PROFESSIONAL GOALS
Format: FULL-TIME
• STUDY A SEMESTER ABROAD AND BECOME A GLOBAL CITIZEN WITH THE BEYOND BORDERS
Intakes: SEPT / FEB
EXPERIENCE

5 Specializations #10 WORLDWIDE 55 Nationalities


MASTER IN MANAGEMENT
Personalize your program FINANCIAL TIMES
in class

www.ie.edu/master-management mim.admissions@ie.edu Follow us on IE MIM Experience

159
157
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT FXML

Opening the dialog the result is (where two persons are entered):

9.3 ABOUT FXML


This chapter has provided a brief introduction to FXML, and although there is more to
explain, the above should be sufficient to use FXML in practice. The question is then what
is gained from using FXML and there are two purposes:

1. to separate the design/definition of the user interface from the Java code
2. to make it easier to develop complex user interfaces

The first follows immediately from the separation of the code for a window in an XML
part and a controller with the Java code. In principle, it is good, but it requires learning
FXML, and although NetBeans provides good support, there is still a lot to learn, and in my
opinion, it’s at least as easy to write the user interface in Java as in FXML. The separation
of the code can easily be achieved by moving the code to event handlers in their own classes
in a controller layer. The conclusion is that I do not find the big gains in using FXML,
and in fact, I feel that the forces are better used by learning JavaFX in detail than using the
power to get good at FXML. It’s my opinion and it’s not necessarily true and I know that
others look different. Therefore, there is only to say, to try and gain your own experiences.

According to what I’ve mentioned above, FXML does not make it easier to write user
interfaces, but it is when using a tool. There is a program called Scene Builder that you can
use to design the user interface. Instead of writing the code itself, you pull components

160
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT FXML
fXml

from
from aa toolbox
toolbox andand place
place them
them inin the
the window
window where
where you
you think
think they they should
should be.
be. The
The tool
tool
will
will then
then form
form the
the FXML
FXML codecode for
for the
the user
user interface,
interface, and
and itit isis in
in this
this context
context that
that FXML
FXML
comes
comes into
into its
its own.
own. The
The product
product Scene
Scene Builder
Builder can
can be
be downloaded
downloaded from from

http://gluonhq.com/products/scene-builder/

and itit isis quite


and quite simple
simple to to install.
install. Of
Of course,
course, you
you should
should learn
learn to
to use
use the
the product,
product, but but also
also itit
isis relatively
relatively easy,
easy, and
and ifif you
you often
often need
need to
to write
write complex
complex user
user interfaces,
interfaces, itit isis worth
worth knowing
knowing
the product
the product as as itit can
can generate
generate significant
significant progress
progress in
in development
development projects.
projects.

161
159
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT A final example

10 A FINAL EXAMPLE
As the final example, I will use the same program as in the previous book, but with the
difference that the program this time should be a desktop application. This means that I
can reuse the class library FunctionsLib, which implements the mathematical functions, as
well as the classes for parsing and evaluating an expression can also be reused. Therefore, I
only have to implement the user interface. The aim of the program is, of course, to show an
example of a JavaFX program, which is slightly larger than the examples that are otherwise
shown in this book.

The program must have the same features as in the previous book and should be basically
used in the same way where the user enters a mathematical expression that the program
can then evaluates. Unlike the previous program, the program should have buttons for the
mathematical functions where a button should do nothing but insert the function name in
the input field of the expression. In the previous program you can save a value in a variable
and the value can be inserted later in an expression. In the new version of the program you
must be able to save an arbitrary expression so that you can insert an expression into an
expression, and it should also be possible to save the program’s variables in a file.

10.1 DEVELOPMENT
The development of the program has been implemented as a form of prototyping, and in
the following I will briefly describe how the development has been completed. From the
start, I have planned the following iterations:

1. First prototype
2. Enhanced prototype
3. Implements the square root and square function
4. Implements Store and Recall
5. Implements the other functions
6. Implements Set Precision
7. Implements the menu item Expressions
8. Implements the File menu
9. Implements missing features
10. Styling the program
11. Refactoring

162
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT A final example

and the goal is that after completing the last iteration, you will have a finished program.
The iterations are small, but after each iteration you have a version of the program that can
be tested and used with the functions that have been implemented.

First prototype
The goal is to write an early version of the program, which should alone be a sketch of the
user interface. The program must therefore not have calculating functions.

Apart from the buttons, the program looks like the application from the previous book.
The window must be resizable, and the two text fields must follow the size of the window,
but the bottom must have a fixed height. The buttons should follow the right edge and
bottom of the window. The File menu must have functions for saving and loading the
variables, while the Functions menu must have a function to change the precision as well
as a function that shows an overview and the variables that have been created.

Enhanced prototype
The result of the next iteration is still a prototype for the user interface, but with some
changes with regard to buttons and with appropriate spacing and padding of the components.

163
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT A final example

Excellent Economics and Business programmes at:

“The perfect start


of a successful,
international career.”

CLICK HERE
to discover why both socially
and academically the University
of Groningen is one of the best
places for a student to be
www.rug.nl/feb/education

164
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT A
A final
fInAl example
eXAmple

To
To the
the right
right of
of the
the buttons
buttons isis aa list
list box
box that
that displays
displays the
the program’s
program’s variables
variables and
and the
the size
size
must
must be
be that
that part
part of
of the
the window
window that that isis not
not used
used for
for buttons.
buttons. Additionally,
Additionally, aa progress
progress bar
bar
has
has been
been added
added because
because some
some thethe calculations
calculations maymay take
take aa long
long time.
time.

Implements
Implements the
the square
square root
root and
and square
square function
function
II have
have added
added aa reference
reference to
to the
the jar
jar file
file FunctionsLib.jar
FunctionsLib.jar from
from the
the final
final project
project in
in the
the previous
previous
book.
book. Then
Then II have
have created
created aa package
package bigcalc.models
bigcalc.models and
and copied
copied the
the files
files Tokens.java
Tokens.java and
and
Expression.java
Expression.java from
from the
the project
project FunctionsEJB
FunctionsEJB to to this
this package.
package. After
After that,
that, the
the entire
entire math
math
should
should be
be in
in place
place and
and the
the required
required calculation
calculation functions
functions should
should bebe available.
available.

II have
have then
then created
created aa package
package bigcalc.ctrls
bigcalc.ctrls and
and here
here aa class
class MainController:
MainController:

package bigcalc.ctrls;

import bigcalc.models.*;

public class MainController


{
private int precision = 200;

public String calculate(String text)


{
try
{
return (new Expression(text, precision)).getValue().toString();
}
catch (Exception ex)
{
return "Error: " + ex.getMessage();
}
}

public int getPrecision()


{
return precision;
}

public void setPrecision(int precision)


{
this.precision = precision;
}
}

165
163
JAVA 14:
JAVA 14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH JAVAFX:
WITH JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT A final
A fInAl example
eXAmple

In the
In the class
class BigCalc,
BigCalc, event
event handlers
handlers are
are assigned
assigned to
to the
the following
following buttons:
buttons:

--- Sqr
Sqr
--- Sqrt
Sqrt
--- Clear Result,
Clear Result, which
which deletes
deletes the
the content
content of
of the
the upper
upper field
field for
for the
the result
result
--- Clear Editor,
Clear Editor, which
which deletes
deletes the
the content
content og
og the
the enter
enter field
field
--- Enter
Enter

ItIt isis all


all simple
simple event
event handlers.
handlers. Then
Then you
you can
can perform
perform arithmetic
arithmetic and
and evaluate
evaluate expressions,
expressions,
and the
and the calculator
calculator isis in
in principle
principle complete.
complete. In
In particular,
particular, you
you can
can paste
paste text
text into
into the
the editor
editor
by clicking
by clicking the
the buttons
buttons Sqr Sqr and
and Sqrt.
Sqrt.

Implements Store
Implements Store and
and Recall
Recall
IfIf you
you click
click the
the STO
STO button,
button, you
you should
should get
get the
the following
following dialog
dialog box:
box:

where to
where to enter
enter the
the name
name ofof the
the variable.
variable. IfIf you
you click
click OK,
OK, thethe last
last result
result that
that isis calculated
calculated
isis saved.
saved. If,
If, on
on the
the other
other hand,
hand, youyou have
have checked
checked the the Store
Store Expression
Expression check
check box,box, itit isis the
the
expression that
expression that isis entered
entered inin the
the editor
editor field
field that
that isis saved.
saved. After
After clicking
clicking OKOK andand the
the desired
desired
value isis assigned
value assigned to to the
the variable,
variable, the
the list
list box
box isis updated
updated (the (the list
list box
box to
to the
the left
left of
of the
the buttons).
buttons).

In order
In order to
to keep
keep track
track of
of the
the variables,
variables, the
the following
following model
model class
class has
has been
been added:
added:

package bigcalc.models;

import java.util.*;

public class Memory implements Iterable<String>


{
private Map<String, String> variables = new TreeMap();

164
166
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
WITH 14: DEVELOPMENT
JAVAFX: SOFTWAREOFDEVELOPMENT
APPLICATIONS A final example
WITH JAVAFX: SOFTWARE DEVELOPMENT A fInAl eXAmple

public void store(String key, String value)


{
variables.put(key, value);
}

public String getValue(String key)


{
return variables.get(key);
}

public boolean remove(String key)


{
return variables.remove(key) != null;
}

public Iterator<String> iterator()


{
return variables.keySet().iterator();
}
}

If you click on a variable in the list box, the corresponding value is inserted in the editor
If you click on a variable in the list box, the corresponding value is inserted in the editor
field (at the cursor’s position). The same syntax is used as in the previous program, that
field (at the cursor’s position). The same syntax is used as in the previous program, that

American online
LIGS University
is currently enrolling in the
Interactive Online BBA, MBA, MSc,
DBA and PhD programs:

▶▶ enroll by September 30th, 2014 and


▶▶ save up to 16% on the tuition!
▶▶ pay in 10 installments / 2 years
▶▶ Interactive Online education
▶▶ visit www.ligsuniversity.com to
find out more!

Note: LIGS University is not accredited by any


nationally recognized accrediting agency listed
by the US Secretary of Education.
More info here.

167
165
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT AA final
fInAl example
eXAmple

isis @A1,
@A1, and
and thethe difference
difference isis that
that the
the value
value can
can be
be aa value
value or
or an
an expression.
expression. This
This means
means
that
that the
the controller
controller must
must be be updated
updated so so that
that values
values for
for variables
variables are
are substituted
substituted before
before the
the
expression
expression isis sent
sent to
to the
the parser.
parser.

IfIf you
you click
click the
the RCL
RCL button,
button, you
you get
get the
the following
following window
window where
where two
two variables
variables were
were created:
created:

IfIf you
you click
click on
on the
the name
name of of aa variable,
variable, the
the window
window closes
closes and
and the
the value
value of
of the
the variable
variable isis
inserted
inserted inin the
the editor
editor field
field at
at the
the cursor’s
cursor’s position.
position. IfIf you
you check
check one
one or
or more
more checkboxes
checkboxes
and
and click
click the
the button
button Remove,
Remove, these
these variables
variables will
will be
be deleted.
deleted.

Center
Center in
in the
the window
window isis aa ListView
ListView that
that isis created
created as
as follows:
follows:

ListView view = new ListView();


for (String key : memory)
{
CheckBox check = new CheckBox("");
check.setPrefWidth(20);
HBox pane = new HBox(10, check);
pane.setAlignment(Pos.CENTER_LEFT);
Label name = new Label(key);
name.setOnMouseClicked(ev -> selectVariable(key));
name.setPrefWidth(60);
Label value = new Label(memory.getValue(key));
pane.getChildren().add(name);
pane.getChildren().add(value);
view.getItems().add(pane);
}

Here you
Here you should
should note
note that
that aa ListView
ListView can
can contain
contain anything,
anything, and
and especially
especially aa layout
layout pane
pane
with components.
with components. ItIt isis thus
thus an
an extremely
extremely flexible
flexible component,
component, and
and the
the list
list box
box on
on the
the main
main
window isis initially
window initially initialized
initialized in
in the
the same
same way.
way.

168
166
JAVA
JAVA14:
14:DEVELOPMENT
DEVELOPMENTOF
OFAPPLICATIONS
APPLICATIONS
WITH
WITHJAVAFX:
JAVAFX:SOFTWARE
SOFTWAREDEVELOPMENT
DEVELOPMENT AAfinal
fInAlexample
eXAmple

In
In principle,
principle, this
this dialog
dialog box
box contains
contains thethe same
same information
information as as the
the list
list box
box to
to the
the left
left
of
of the
the buttons,
buttons, but
but the
the dialog
dialog isis included
included partly
partly to
to delete
delete variables
variables and
and partly
partly to
to give
give aa
better
better overview.
overview.

Implements
Implements the
the other
other functions
functions
This
This iteration
iteration isis simple
simple as as the
the remaining
remaining buttons
buttons must
must do do thethe same
same as
as for
for Sqr
Sqr and
and Sqrt,
Sqrt,
where
where only
only aa text
text must
must be be inserted
inserted into
into the
the editor
editor field
field at
at the
the cursor’s
cursor’s position.
position. The
The only
only
challenge
challenge isis that
that itit isis the
the right
right text.
text.

However,
However,the theimpact
impactof ofthe
theprogress
progressbarbarmust
mustbebeimplemented.
implemented.IIhave havechanged
changedthe thecomponent
component
to
to a ProgressIndicator, which is constantly running, but from the start is invisible. When
a ProgressIndicator, which is constantly running, but from the start is invisible. When aa
calculation
calculation isis started
started (clicked
(clicked Enter),
Enter), the
the component
component isis made
made visible
visible and
and itit becomes
becomes invisible
invisible
again
againwhenwhenthethecalculation
calculationisiscompleted
completedand andthe
theuser
userinterface
interfaceisisupdated.
updated.TheTheonly
onlychallenge
challenge
isis get
get the
the the
the user
user interface
interface (the
(the ProgressIndicator)
ProgressIndicator) updated,
updated, andand the
the calculation
calculation mustmust be
be
performed in its own
performed in its own thread:thread:

private void calculate(ActionEvent e)


{
String expression = txtEditor.getText().trim();
calculator = new Thread()
{
public void run()
{
lastValue = ctrl.calculate(expression, memory);
updateResult();
}
};
progress.setVisible(true);
calculator.start();
}

private void updateResult()


{
String text = txtDisplay.getText();
if (text.length() > 0) text += "\n";
txtDisplay.setText(text + lastValue);
calculator = null;
progress.setVisible(false);
}

After this iteration, the machine is in principle completed, but with a fixed precision of 200.
After this iteration, the machine is in principle completed, but with a fixed precision of 200.

169
167
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT A final example

Implements Set Precision


This function opens a simple dialog box where you can enter the desired precision:

If you click OK, both the controller and the status bar in the main window must be updated.
The function has been moved from the menu to a button above the Enter key. The menu
has been changed so that under Functions there is a menu item for each of the program’s
buttons. The reason is partly to have a better description of the individual functions and
to define key combinations for all functions and commands.

170
JAVA
JAVA14:
14:DEVELOPMENT
DEVELOPMENTOF
OFAPPLICATIONS
APPLICATIONS
WITH
WITHJAVAFX:
JAVAFX:SOFTWARE
SOFTWAREDEVELOPMENT
DEVELOPMENT AAfinal
fInAlexample
eXAmple

Implements
Implements the
the menu
menu item
item Expressions
Expressions
This
This iteration
iteration isis empty,
empty, as
as the
the function
function corresponds
corresponds to
to aa click
click on
on RCL,
RCL, and
and the
the function
function isis
already
alreadyimplemented.
implemented.SinceSinceRCL RCLalso
alsohas
hasaamenu
menuitem,
item,the
thefunction
functionalready
alreadyexists
existsin
inthe
themenu.
menu.

Implements
Implements the
the File
File menu
menu
Five
Five functions
functions must
must be
be implemented,
implemented, all
all located
located under
under the
the File
File menu:
menu:

1.
1. Save,
Save, which
which saves
saves all
all variables
variables in
in an
an existing
existing file
file
2.
2. Save
Save as,
as, which
which saves
saves all
all variables
variables in
in aa new
new file
file
3.
3. Open,
Open, which
which opens
opens aa file
file with
with variables,
variables, that
that ealier
ealier are
are saved
saved
4.
4. New,
New, which
which deletes
deletes all
all existing
existing variables
variables
5.
5. Exit,
Exit, which
which terminates
terminates the the program
program

Variables
Variablesmust
mustbe besaved
savedwith
withsimple
simpleobject
objectserialization.
serialization.Therefore,
Therefore,the
theclass
classMemory
Memoryisispartly
partly
defined
defined Serializable,
Serializable, and
and in
in addition,
addition, there
there are
are added
added two
two static
static methods:
methods:

public static boolean store(Memory memory, String filename)


{
try (ObjectOutputStream stream =
new ObjectOutputStream(new FileOutputStream(filename)))
{
stream.writeObject(memory);
return true;
}
catch (Exception ex)
{
return false;
}
}

public static Memory load(String filename)


{
try (ObjectInputStream stream =
new ObjectInputStream(new FileInputStream(filename)))
{
return (Memory)stream.readObject();
}
catch (Exception ex)
{
return null;
}
}

169
171
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT A final example

Then it’s simple to implement the 5 event handlers using a FileChooser component.

Implements missing features


There is not much that are missing, but the following should be added:

1. There should be warnings if you try to overwrite existing variables by loading


variables from a file or closing the program and the variables are not been saved.
2. Similarly, there should be a warning if you delete the content of the result field,
and accordingly if you delete variables in the dialog that shows the list of variables
(the command RCL). The same applies to the dialog boxes for entering the name
of a variable and the dialog for change the precision if you enter an illegal value.
3. If you use many significant digits (heigh precision), a calculation can take a long
time and therefore a timeout should be defined so that the program giving up
after the timeout.

The first point is simple to solve and is primarily about include a boolean variable that keeps
track of changes in the program’s variables. The problem is thus limited to ensuring that
this variable is set at the correct places and then test the variable in the event handlers for
the File menu. Additionally, you can override the stop() method and test the variable there
so that you do not close the program without a warning if there are non-saved variables.

The second point is similarly simple and refers to displaying a confirmation box in the event
handler that deletes the content of the result field, as well as a test in the three dialog boxes.

The last problem, on the other hand, is not quite simple to solve. First I have in the
controller class (MainController) included a property timeout, which indicates the number
of seconds for the timeout value. It is as default 15. Next, I have expanded the program
with the following dialog box:

where you can enter the timeout value. There is no button for the dialog, but it is opened
from the menu or with a shortcut key.

172
JAVA
JAVA 14:
14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT A
A final
fInAl example
eXAmple

When
When you
you click
click the
the Enter
Enter button
button in
in the
the main
main window,
window, the
the following
following events
events are
are performed:
performed:

private void calculate(ActionEvent e)


{
String expression = txtEditor.getText().trim();
Thread calculator = new Thread()
{
public void run()
{
cmdCalc.setDisable(true);
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Void> task = executor.submit(new Calculator());
try
{
task.get(ctrl.getTimeout(), TimeUnit.SECONDS);
}
catch (Exception ex)
{
lastValue = "Timeout";
}
executor.shutdownNow();
Platform.runLater(new Runnable()
{

173
171
JAVA 14: DEVELOPMENT OF APPLICATIONS
JAVA
JAVA 14:
WITH 14: DEVELOPMENT
DEVELOPMENT
JAVAFX: OF
SOFTWARE APPLICATIONS
OFDEVELOPMENT
APPLICATIONS A final example
WITH
WITH JAVAFX:
JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT A
A fInAl
fInAl eXAmple
eXAmple

@Override
@Override
public
public void
void run()
run()
{{
updateResult();
updateResult();
cmdCalc.setDisable(false);
cmdCalc.setDisable(false);
}}
});
});
}}
};
};
progress.setVisible(true);
progress.setVisible(true);
calculator.start();
calculator.start();
}}

It looks a bit complex. The calculation is performed by a method in an Expression object in


the controller and is the method that takes time, and if executed directly, it will block the
main window,
main window, which
which will
will mean
mean that
that the
the progress
progress indicator
indicator does
does not
not run.
run. The
The calculation
calculation
must therefore
must therefore be
be performed
performed in in its
its own
own thread,
thread, which
which is
is the
the thread
thread calculator.
calculator. In
In Java,
Java, you
you
can not directly interrupt a running thread, which must happen in the case of a timeout.
The problem can be solved with an Executor and a Future object (possibly see Java 8). The
thread calculator
thread calculator therefore
therefore starts
starts with disabling the button Enter, and then an Executor
Executor object
object
is created
is created that
that is
is used
used to
to start
start aa task
task of
of the
the type
type Calculator:
Calculator:

class
class Calculator
Calculator implements
implements Callable<Void>
Callable<Void>
{{
public
public Void
Void call()
call()
{{
try
try
{{
lastValue
lastValue == ctrl.calculate(txtEditor.getText().trim(),
ctrl.calculate(txtEditor.getText().trim(), memory);
memory);
}}
catch
catch (Exception
(Exception ex)
ex)
{{
lastValue
lastValue == "Error";
"Error";
}}
return
return null;
null;
}}
}}

It
It is
is then
then its
its call()
call() method
method that
that performs
performs thethe calculation.
calculation. After
After this
this task
task has
has been
been created
created (in
(in
the
the thread
thread calculator)
calculator) the
the thread
thread is
is set
set to
to wait
wait for
for the
the task
task to
to be
be performed
performed oror aa timeout
timeout occurs.
occurs.
In
In the case of the last the result is defined as the text Timeout, after which is executed an
the case of the last the result is defined as the text Timeout, after which is executed an

executor.shutdownNow();
executor.shutdownNow();

174
172
172
JAVA 14:
JAVA 14: DEVELOPMENT
DEVELOPMENT OF
OF APPLICATIONS
APPLICATIONS
WITH JAVAFX:
WITH JAVAFX: SOFTWARE
SOFTWARE DEVELOPMENT
DEVELOPMENT A final
A fInAl example
eXAmple

This causes
This causes that
that threats
threats performed
performed by by the
the task
task to
to terminate,
terminate, and
and even
even ifif itit isis still
still running
running
due to
due to aa timeout.
timeout. Hereafter
Hereafter the
the following
following method
method isis called
called which
which updates
updates the the result:
result:

private void updateResult()


{
String text = txtDisplay.getText();
if (text.length() > 0) text += "\n";
txtDisplay.setText(text + lastValue);
progress.setVisible(false);
txtEditor.requestFocus();
position = txtEditor.getText().trim().length();
txtEditor.selectRange(position, position);
}

and
and the
the button
button will
will be
be enabled
enabled agian.
agian. After
After the
the thread
thread calculator
calculator isis defined,
defined, itit isis started
started and
and
the result is that the calculation is performed in a thread (of a task object)
the result is that the calculation is performed in a thread (of a task object) that is startedthat is started
by
by the
the thread
thread calculator
calculator that
that starts
starts when
when clicking
clicking the
the Enter
Enter button.
button.

Styling
Styling the
the program
program
After
After the
the above
above iterations,
iterations, all
all windows
windows and
and nodes
nodes are
are shown
shown onon basis
basis of
of the
the default
default styles
styles
in
in JavaFX, and often, by a program of the current kind, it will be quite good, but if you
JavaFX, and often, by a program of the current kind, it will be quite good, but if you
want
want toto put
put your
your own
own touch
touch onon how
how the
the components
components appear
appear oror for
for some
some reason
reason wantwant to to
change
change the
the specific
specific components
components looklook and
and feel,
feel, you
you can
can add
add aa style
style sheet.
sheet. ItIt isis preferable
preferable
not
not to directly assign values to properties in the code, as a style sheet makes it much easier
to directly assign values to properties in the code, as a style sheet makes it much easier
to maintain the code.
to maintain the code.

There
There are
are several
several strategies,
strategies, but
but you
you can
can proceed
proceed as
as follows.
follows. The
The program
program (the
(the main
main window)
window)
has the following groups of components:
has the following groups of components:

--- 11 TextArea
TextArea forfor the
the display
display (the
(the result)
result)
--- 11 TextField
TextField to to the
the editor
editor field
field
--- 11 ListView to variables
ListView to variables
--- 11 Button
Button toto the
the Enter
Enter button
button
--- 55 Button
Button controls
controls to to commands
commands (Clr (Clr Result,
Result, Clr
Clr Editor,
Editor, Precision,
Precision, RCL,
RCL, STO)
STO)
--- 22 Button
Button controls
controls to to consts
consts (Pi,
(Pi, e)
e)
--- 36 Button controls to functions
36 Button controls to functions
--- 77 Menu
Menu controls
controls
--- 41
41 MenuItem
MenuItem controls
controls
--- 11 ProgressIndicator
ProgressIndicator

173
175
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT A final example

-- 1 Label to the text in the status line


-- 1 Label to precision
-- 1 Label to the filename
-- 1 Label to the variable name in the list box
-- 1 Label to the variable valie in the list box

You can then in a style sheet define a class (an empty class) for each of these groups (15
classes in total) and then associate these classes with the individual components. You can then
write the styles you want to use and the advantage is that you can change the presentation
of controls without changing the Java code, and as the most important thing, you can
delegate the work to developers with special skills in styling.

In this case, I have added a style sheet named mainstyles.css and written a few styles – and
maybe even most for the example’s sake.

You can then repeat it for all the application’s windows and dialogs, and maybe use the
same style sheet for all or most dialogs. That way, you only have to write styles somewhere,
and all of the application’s dialog boxes have the same look and feel. In this case, I have
added a style sheet named dlgstyles.css, which is used by all dialogs. In many examples, you

Join the best at Top master’s programmes


• 3
 3rd place Financial Times worldwide ranking: MSc
the Maastricht University International Business
• 1st place: MSc International Business
School of Business and • 1st place: MSc Financial Economics
• 2nd place: MSc Management of Learning

Economics! • 2nd place: MSc Economics


• 2nd place: MSc Econometrics and Operations Research
• 2nd place: MSc Global Supply Chain Management and
Change
Sources: Keuzegids Master ranking 2013; Elsevier ‘Beste Studies’ ranking 2012;
Financial Times Global Masters in Management ranking 2012

Maastricht
University is
the best specialist
university in the
Visit us and find out why we are the best! Netherlands
(Elsevier)
Master’s Open Day: 22 February 2014

www.mastersopenday.nl

176
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT A final example

may want to use a single style sheet, which is used by all windows, and of course (at least
for small programs) it may be appropriate.

Refactoring
Now the program is in principle complete and consists of the following files:

I have previously argued that in this place you should conduct a code review, inspecting the
code, adding comments, removing disabilities, and more. This code review often has character
of a refactoring, which may result in code being moved to new classes or reorganizing the
code in another way. Especially if the program is developed through many small iterations
with the character of prototyping as in this case, there is a great risk that it may go beyond
the architecture, and in particular there is a risk that the class of the main window swells
up and becomes inappropriately design. For the sake of future maintenance, therefore,
refactoring is important, and you should focus on the following:

-- If there are import statements that are no longer necessary (NetBeans shows which
ones), they should be removed.
-- If there are variables that are no longer used, they should also be deleted.
-- If there is code (such as methods) that are not used, it should be removed.
-- Has instance variables and methods appropriate names. If not, consider changing
the names so that they better reflect the use.
-- Consider visibility, so only what it’s going to be public is public while the rest is
private and possibly protected.

177
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT A final example

-- Are variables and properties located in the right place (in the right classes) and here
you must have the MVC pattern in mind. Often the user interface will contain
variables that should be moved to the controller or model.
-- Pay special attention to code repetition where the same code is written in several
places. Such a code should typically be moved to its own method, and the code
repetitions can then be replaced by the call of this method.
-- Pay attention to the size of classes. If classes are very large, such as many hundred
of lines or more, you might want to consider splitting up the class into several
classes. Not that you must necessarily, but a class on a thousand lines or more is
hard to overlook.
-- Be aware of event handlers, as they tend to contain code related to business logic,
and if necessary, this code should be moved to controller classes (possibly to the
model). In general, event handlers should be as simple as possible and contain only
code that directly concerns the user interface. It’s a tough balance, since delegation
of the code to the controller and model layers can also lead to code that is difficult
to read and that the user interface needs to be observer for the controller and model.
However, it should be noted that the user interface should contain only what is
necessary to update the components.

And so: Refactoring is an important activity for future maintenance, but make sure that the
process does not introduce new errors in the program. The program must then be tested
again after the activity is completed.

And then there are the comments, which are also part of the refactoring process or rather
the maintenance of the comments. I have previously argued the importance of comments
and especially the process of writing the comments. These views are still valid, but if you
see my program examples (what the readers hopefully do), I have to admit that there is a
long line between the comments. Should the truth come true, I must also admit that I am
a bit ambivalent with regard to comments: I know it’s right to comment on the code, but
I do not do that often, so some remarks about this problem.

It’s a big job to write comments – at least if you have to make it complete, and then the
comments also has to tell you something. You must therefore necessarily refer to whether
it is worth the work. Comments documents the code and it is certainly important, but
I find that good program architecture and good names for variables and methods are far
more important – it is also a form of comments. The goal of all is to make the code easier
to read and understand, and here I find that the things I have mentioned above regarding
refactoring, exceeds the value of comments. Comments have definitely their applications, but
with good names and a good architecture, there is a tendency for comments to commenting

178
JAVA 14: DEVELOPMENT OF APPLICATIONS
WITH JAVAFX: SOFTWARE DEVELOPMENT A final example

on self-esteem and comments make comments for their own sake, and if so, it’s not worth
the effort – then there is hardly anyone who will pay for the assignment.

Now it’s probably not either, but to explain a little about my wings, I will mention that
when I have to read and understand foreign code, one of the first things I do is to delete
all comments. They simply seem disturbing to me – at least if it’s a nice code. Is that the
way it matters, of course, it does not make much sense of writing comments. Of course, it
also has something to do with which code it is, where comments of the code in the user
interface are rarely valuable, where comments of complex algorithms in control and model
days may be required.

I know that not everyone will agree with these views, but at least they explain why my code
often lacks comments, which also reflects that much of what I should write as comments
is a part of the text in the books.

179

You might also like