JavaFX Essentials - Sample Chapter
JavaFX Essentials - Sample Chapter
ee
Sa
pl
Preface
This book, as its title (JavaFX 8 Essentials) suggests, is a pragmatic book that
provides you with a robust set of essential skills that will guide you to become
confident enough to rapidly build high-performance JavaFX 8 client applications.
These applications take advantage of modern GPUs through hardware-accelerated
graphics while delivering a compelling, complex, and fancy rich-client GUI for your
customer, which will impress them quite a bit.
Learning the JavaFX 8 essentials is the first step to plunging into creating
applications that most importantly run on any platform, from the desktop, Web,
mobile, tablets, to embedded devices such as Arduino, Raspberry Pi, and multi-core
development. Following Java's Write once, run anywhere paradigm, JavaFX also
preserves the same. Because JavaFX 8 is written totally from scratch in the Java
language, you will feel at home.
Most of the chapters are a fast-paced guide that will help you get a head
start on Java GUI programming, leveraging JavaFX 8 and deploying and running
on any platform.
While working through the book examples, you will find code is written with JavaFX
8 on Java 8 (yes, Java SE 8) so that the new APIs and language enhancements will
help you become a more productive developer. Having said this, it will be handy
(and I encourage you to go for this) to explore all of the new Java 8 capabilities.
Finally, yet importantly, you will be able to develop amazing touch-less interactive
motion applications with JavaFX that interact with Leap motion devices.
Preface
Preface
We will also discuss the relationship between JavaFX and HTML5, which is
important because they complement each other. JavaFX's rich client APIs, coupled
with HTML5's rich web content, create a user experience resembling a RIA Web
application with the characteristics of native desktop software.
Chapter 4, Developing a JavaFX Application for Android, as we see a rise in non-pc
clients, mobile phones and tablets are gaining market share. JavaFX 8 can deliver a
rich client application for Web and desktop. If you write a JavaFX application, make
sure you want it to run on as many devices as possible. This chapter will give you
essential hands-on experience and knowledge about SDKs that allow users to create
native applications for Android mobile phones.
Chapter 5, Developing a JavaFX Application for iOS, is an extension to the previous
chapter. If you write a JavaFX application for Android, be sure you want it to run
on as many iOS devices as possible. This chapter will give you essential hands-on
experience and knowledge about SDKs that allow them to create native applications
for Apple iOS.
Chapter 6, Running JavaFX Applications on the Raspberry Pi, will provide you with all
the necessary skills and knowledge to develop a JavaFX 8 application that runs on a
credit card-sized computer, the Raspberry Pi board. As the Internet of things (IoT)
has become a hot topic of late. Java was made for the Internet of things literally.
Chapter 7, Monitoring and Controlling Arduino with JavaFX, covers another
kind of Internet of everything (IoT). Arduino is an open-source electronics
prototyping platform, delivering low-cost prototyping platforms to support
both the do-it-yourself concept and the maker movement.
This chapter will provide you with all the necessary skills and knowledge to quickly
use JavaFX along with an Arduino board to develop desktop applications for
monitoring data coming from the real world or controlling real devices.
Chapter 8, Interactive Leap Motion Apps with JavaFX, will make you learn about gesture
recognition. You will discover an awesome gadget, the Leap Motion device, which
will allow a touch-less approach to develop enhanced JavaFX applications.
Machine user input interfaces are becoming increasingly less mouse-centric, in favor
of multi-touch and even touch-less input. Gestures are one of the ways humans can
communicate with machines naturally these days.
Preface
Appendix, Become a JavaFX Guru, will make you find many useful links and references
that will help you gain further knowledge about all things JavaFX.
At the end of this chapter, make sure to check out the many frameworks, libraries,
and projects that use JavaFX in production today.
JavaFX goals
JavaFX came to light with a primary goal to be used across many types of devices,
such as embedded devices, smartphones, TVs, tablet computers, and desktops.
JavaFX also follows Java's write once, run anywhere paradigm.
JavaFX 8 is written totally from scratch in Java language, it makes you feel at home.
Therefore, applications written in JavaFX can be deployed on desktops, laptops, the
Web, embedded systems, mobiles, and tablets.
Embedded systems are no longer supported by Oracle; it is left to companies like
ARM and others to support it. Mobile devices have never been supported from
JavaFX 2.x to 8.x; the support exists now only because of OpenJFX. The community
has benefitted from open source bringing JavaFX to mobile environments.
For more about OpenJFX, visit https://wiki.openjdk.java.net/display/
OpenJFX/Main.
JavaFX is a set of graphics and a media package that enables developers to design,
create, test, debug, and deploy rich client applications that operate consistently
across diverse platforms, in one bundle, without the need for many separate
libraries, frameworks, and APIs to achieve the same goal. These separate libraries
include media, UI controls, WebView, 3D, and 2D APIs.
So if you are a Java frontend developer, an experienced Java Swing, Flash/Flex,
SWT, or web developer looking to take your client-side applications to the next
level, and you want to develop an attractive and complex user interface for your
customer, then you are on track learning JavaFX skills this book is for you.
[2]
Chapter 1
Getting started
This chapter is an introduction to JavaFX 8; we have already talked about JavaFX 8
as a technology and why you should care about it.
Next, we will navigate its history, exploring its core features and where it could
be used.
Before you start using this book to learn JavaFX 8, we will go through the
preparation of your development environment by installing various required
software bundles, to be able to compile and run many of its examples.
In this chapter, you will learn how to install the required software, such as the
Java Development Kit JDK and the NetBeans Integrated Development
Environment (IDE).
After installing the required software, you will begin by creating a traditional Hello
JavaFX 8 example. Once you feel comfortable with the development environment,
as a final verification that we are on the right track, we will walk through the Hello
JavaFX 8 source code to understand the basic JavaFX 8 application architecture.
If you are already familiar with the installation of the JDK and the
NetBeans IDE, you can skip to Chapter 2, JavaFX 8 Essentials and
Creating a custom UI, which covers JavaFX 8 fundamentals and how
to create a custom UI component.
JavaFX history
You might believe JavaFX is quite a new technology, but it actually isn't. JavaFX
has been here for a long time; unofficially since 2005. Ever since Sun Microsystems
acquired the company SeeBeyond, there has been a graphics-rich scripting language
known as F3 (Form Follows Function), which was created by engineer Chris Oliver.
At the JavaOne 2007 conference, Sun Microsystems officially unveiled JavaFX as
the language's name instead of F3. During the period 2007 to 2010, Oracle acquired
many big companies like BEA Systems, JD Edwards, Siebel Systems, and so on. I was
working for Oracle with the responsibility of integrating different customer support
channels to the Oracle support website MetaLink, as it was called at that time.
[3]
[4]
Chapter 1
The JavaFX APIs are available as a fully integrated feature of the Java SE Runtime
Environment (JRE) and JDK. The JDK is available for all major desktop platforms
(Windows, Mac OS X, Solaris, and Linux), therefore JavaFX will also run on all major
desktop platforms.
Relating to JavaFX 8, it supports the following APIs:
3D graphics
Printing APIs.
JavaFX features
The following features are included in JavaFX 8 and later releases as per JavaFX's
official documentation:
Java APIs: JavaFX is a Java library that consists of classes and interfaces
that are written in Java code.
Built-in UI controls and CSS: JavaFX provides all the major UI controls,
and some extra uncommon controls like charts, pagination, and accordion
that are required to develop a full-featured application. Components can be
skinned with standard web technologies such as CSS.
Canvas API: You can draw directly inside a JavaFX scene area using the
Canvas API, which consists of one graphical element (node).
[5]
The new Modena theme is now the default theme for JavaFX applications.
The API enables you to embed Swing content into JavaFX applications with
the new SwingNode class, which improves the Swing interoperability feature.
[6]
Chapter 1
The 3D graphics library has been enhanced with several new API classes.
Major updates have been added to the Camera API class in this release.
Now JavaFX 8 supports rich text capabilities. These include bidirectional and
complex text scripts such as Thai and Hindi in UI controls, and multiline,
multistyle text in text nodes.
In Appendix, Become a JavaFX Guru, I have provided a list of all the references
(links, books, magazines, articles, blogs, and tools) and real JavaFX 8 production
applications you will need to become a JavaFX guru.
The following figure shows the Ensemble8.jar application built using JavaFX 8,
showing examples dealing with various JavaFX 8 components, topics and concepts.
More interestingly, the source code is available to learn from and modify consult
the last chapter to see how to install this application.
JavaFX 8 applications
[7]
There are many topics covered by the application, especially the new JavaFX 8
3D APIs, which can be found under the Graphics 3D section as seen in the
following figure:
JavaFX 8 3D applications
[8]
Chapter 1
Download the latest Java SE 8u45 JDK or higher from the following location:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Download and install NetBeans 8.0.2 or higher from the following link https://
netbeans.org/downloads, though the NetBeans IDE All Bundle is recommended,
you can use the Java EE bundle as well, as shown in the figure:
Mac OS X (64-bit)
Linux (32- and 64-bit), Linux ARMv6/7 VFP, HardFP ABI (32-bit)
In the following steps, the Java SE 8u45 JDK 64-bit version (at the time of writing)
on the Mac OS X Yosemite (10.10.3) operating system will be used as an example.
[9]
The steps are similar on other operating systems and JDK versions. However, if your
environment is different, refer to the following link for additional details:
http://docs.oracle.com/javase/8/docs/technotes/guides/install/toc.
html
[ 10 ]
Chapter 1
2. Begin the setup of the Java 8 JDK. The screen in the following screenshot will
appear at the beginning of the installation process. Click on the Continue
button, next on the Installation type screen wizard, click on Install to begin
the installation.
3. Once you hit Install, you may be asked to supply your password. Supply it,
click on Ok and the installation will proceed with a progress bar, as shown in
following figure:
4. The setup will complete the installation of the Java 8 SE Development Kit.
click on the Close button to exit.
[ 11 ]
JAVA_HOME: This tells your operating system where the Java installation
directory is.
PATH: This specifies where the Java executable directory resides. This
environment variable lets the system search paths or directories containing
executable files. The Java executables reside in the bin directory under the
JAVA_HOME home directory.
To make JAVA_HOME and PATH more permanent, you will want to add them to
your system in such a way that they are always made available whenever you boot
or log in. Depending on your operating system, you will need to be able to edit
environment variable names and values.
In the Windows environment, you can use the keyboard shortcut Windows logo key +
Pause/Break key and then click on Advanced system settings to display the Systems
Property dialog.
Next, click on Environment Variables. This is where you can add, edit, and delete
environment variables. You will add or edit the JAVA_HOME environment variable
by using the installed home directory as the value. Shown in this screenshot is the
Environment Variables dialog on the Windows operating system:
[ 12 ]
Chapter 1
On Linux and other Unix operating systems that use Bash shell
environments, launch a terminal window and edit either the ~/.bashrc or
~/.profile file to contain the export commands:
export JAVA_HOME=/usr/java/jdk1.8.0
export PATH=$PATH:$JAVA_HOME/bin
On Linux and other Unix operating systems that use C shell (csh)
environments, launch a terminal window and edit either the ~/.cshrc or
~/.login file to contain the setenv commands:
setenv JAVA_HOME /usr/java/jdk1.8.0_45
setenv PATH ${JAVA_HOME}/bin:${PATH}
Once you've set up your path and the JAVA_HOME environment variables, you
will want to verify your setup by launching a terminal window and executing the
following two commands from the command prompt:
java -version
javac version
[ 13 ]
[ 14 ]
Chapter 1
5. The NetBeans IDE installation processes will begin. The following screenshot
shows the installation progress bar:
Installation progress
Setup complete
[ 15 ]
[ 16 ]
Chapter 1
NetBeans opens the HelloJavaFX.java file and populates it with the code
for a basic "Hello World" application.
You will find that this version of code has been modified a bit
from the one NetBeans actually creates, and you can compare
them to find differences, but they have the same structure. I did
that to show the result on the text node on the Scene instead
of the console when clicking on the Say 'Hello World' button.
For that, a VBox container has also been used.
4. Right-click on the project and click on Run from the menu as shown here:
5. NetBeans will compile and run the application. The output should be as
shown in the following screenshot:
[ 17 ]
6. Click on the button and you should see the following result:
Here is the modified code of the basic Hello world application (HelloJavaFX.java):
import
import
import
import
import
import
import
javafx.application.Application;
javafx.scene.Scene;
javafx.scene.control.Button;
javafx.scene.text.Text;
javafx.stage.Stage;
static javafx.geometry.Pos.CENTER;
javafx.scene.layout.VBox;
/**
* @author mohamed_taman
*/
public class HelloJavaFX extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
Text message = new Text();
btn.setText("Say 'Hello World'");
btn.setOnAction(event -> {
message.setText("Hello World! JavaFX style :)");
});
[ 18 ]
Chapter 1
VBox root = new VBox(10,btn,message);
root.setAlignment(CENTER);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello JavaFX 8 World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
How it works
Here are the important things to know about the basic structure of a
JavaFX application:
The main class for a JavaFX application should extend the javafx.
application.Application class. The start() method is the main
The VBox is used here as the container that arranges its content nodes
vertically in a single column with multiple rows. We have added the button
btn control to the first row in the column, then the text message control to
the second row on the same column, with vertical space of 10 pixels, as in the
following code snippet:
VBox root = new VBox(10,btn,message);
root.setAlignment(CENTER);
[ 19 ]
We set the button control with text, plus an event handler to set the message
text control to Hello World! JavaFX style :) when the button is clicked on.
You might note a strange code syntax written in Java, with no compiler
errors. This is a Lambda expression, which has been added to Java SE 8,
and we are going to talk about it briefly in Chapter 2, JavaFX 8 Essentials
and Creating a custom UI. With a slight comparison to old anonymous inner
classes style, it is cleaner and more concise to use Lambda expression now.
Have a look at this comparison of code:
Old School:
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
message.setText("Hello World! JavaFX style :)");
}
});
New Era:
btn.setOnAction(event -> {
message.setText("Hello World! JavaFX style :)");
});
The main() method is not required for JavaFX applications when the JAR file
for the application is created with the JavaFX Packager tool, which embeds
the JavaFX Launcher in the JAR file.
However, it is useful to include the main() method so you can run JAR files
that were created without the JavaFX Launcher, such as when using an IDE
in which the JavaFX tools are not fully integrated. Also, Swing applications
that embed JavaFX code require the main() method.
Here, in our main() method's entry point, we launch the JavaFX application
by simply passing in the command-line arguments to the Application.
launch() method.
At this point, the program execution occurs on the JavaFX application thread
and not on the main thread. When the start() method is invoked, a JavaFX
javafx.stage.Stage object is available for you to use and manipulate.
[ 20 ]
Chapter 1
Summary
So far, you have learned what JavaFX is and seen its power. You have managed
to download and install both Java 8 JDK and NetBeans IDE. After successfully
installing the prerequisite software, you created a JavaFX Hello World GUI
application through the NetBeans IDE. After learning how to compile and
run a JavaFX application, you did a quick code walkthrough of the source file
HelloJavaFX.java.
Next, in Chapter 2, JavaFX 8 Essentials and Creating a custom you'll learn about JavaFX
8 architecture components and engines, which allow JavaFX applications to run
efficiently and smoothly under the hood. You will also learn about the most common
layout UI components and get an idea about theming your application as a whole
or as individual scene nodes.
We will also be covering Java SE 8's most important feature, Lambda expressions,
and how it works. We will then get insights into Scene Builder as a declarative UI
and productive tool, then learn about generated FXML-based markup document
and how to import it into NetBeans IDE to continue your application logic
implementation to associate it to the already declared UI controls inside
your FXML document.
Finally, you will be able to create a custom UI component that isn't bundled with
default JavaFX 8 UI controls.
[ 21 ]
www.PacktPub.com
Stay Connected: