© Carl Dea, Gerrit Grunwald, José Pereda, Sean Phillips and Mark Heckler 2017

Carl Dea, Gerrit Grunwald, José Pereda, Sean Phillips and Mark Heckler, JavaFX 9 by Example, https://doi.org/10.1007/978-1-4842-1961-4_1

1. Getting Started

Carl Dea, Gerrit Grunwald2, José Pereda3, Sean Phillips4 and Mark Heckler5

(1)Pasadena, Maryland, USA

(2)Münster, Nordrhein-Westfalen, Germany

(3)Arroyo de la Encomienda, Spain

(4)Bowie, Maryland, USA

(5)Godfrey, Illinois, USA

To get started using this book to learn JavaFX 9, you will want to set up your development environment 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 JavaFX HelloWorld example. Once you are comfortable with the development environment, I will walk through the JavaFX HelloWorld source code. Finally, you will get a glimpse of how to package your application as a standalone application to be launched and distributed.

I realize many developers are partial to their IDEs and editors, so I’ve also provided three ways to compile and run the HelloWorld example. In the first way to compile and run code you will be using the NetBeans IDE, in the second way you will learn how to use the command line (terminal window), and thirdly you will be using a build tool called Gradle to compile and launch JavaFX applications. The second and third strategies are for those who are not fond of fancy IDEs. If you are more comfortable with the Eclipse and IntelliJ IDE, you will be happy to know that Gradle can generate the respective project files that will allow your projects to be easily loaded into them.

If you are already familiar with the installation of the Java Development Kit (JDK) , Gradle , and the NetBeans IDE , you can skip to Chapter 2, which covers Java 9 Jigsaw. Let’s get started!

Downloading Required Software

When using this book, you’ll find that many examples may still be written using the Java 8 JDK; however Chapter 2 and a few other chapters will get into Java 9-specific concepts, making the Java 9 JDK a requirement. One of the primary changes to the Java platform is modularity (Jigsaw). Modularity will truly transform your client-side applications. You are probably wondering exactly, “how is it transformed?” Well, imagine building a Java application that occupies a smaller footprint in memory and on disk space. This means users will experience faster load times and a better user experience!

Having said this, go ahead and download Java 9 Java Development Kit (JDK) or later. In this chapter, you will see the steps on installing the JDK on Windows, MacOS X, and Linux. You can download the Java 9 JDK from the following URL:

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Another tool that we have not mentioned in prior editions is Gradle. Gradle has become an industry standard in building projects and artifacts in the real world. Later, I will walk you through how to install Gradle, but for now head over to gradle.org and look for the download link. At the download link you will be presented with two binary distributions. One is just a binary distribution and the other is a full distribution that includes the source code and documentation. The binary distribution is required to build applications, so you’ll want to download it. Go to the following URL to download Gradle’s Build tool:

https://gradle.org/gradle-download

Installing an integrated development environment (IDE) is optional for the book; however if you choose to use an IDE you will be able get all the benefits of code highlighting, code completion, incremental debugging, refactoring, and many modern developer conveniences. The top three IDEs used in the wild are NetBeans, IntelliJ, and Eclipse. Although this book walks you through installing the NetBeans IDE, it doesn’t mean we are partial to NetBeans or any other IDEs. I’ve chosen NetBeans because release schedules are usually on par with the major JDK releases and it’s quite mature, especially when it comes to tooling and JavaFX application development. NetBeans has numerous JavaFX demo projects (example templates) built-in and the Scene Builder tool. Scene Builder is a graphical tool used to build JavaFX UIs visually.

Another pro tip is learning about Gradle tasks, which are capable of generating Java projects for either IntelliJ or Eclipse IDE with a single command. To learn more about Gradle tasks that can automatically set up IntelliJ and Eclipse projects, visit the following links:

The following are URLs to download your favorite IDE :

Currently, JavaFX 9 from Oracle corp. runs on the following operating systems :

  • Windows OS (Vista, 7, 8, 10) 32- and 64-bit

  • MacOS X (64-bit)

  • Ubuntu Linux 12.x - 13.x (32- and- 64-bit)

To see a detailed listing of all the supported operating systems, visit the following link:

http://jdk.java.net/9/supported

While you may not see your supported operating system or hardware, you will be happy to know about the OpenJDK and OpenJFX projects, which allow you to build Java and JavaFX yourself! To learn more about OpenJDK or OpenJFX, visit the following URLs:

After downloading the appropriate software versions for your operating system, you will install the Java 9 JDK, Gradle, and/or your chosen IDE .

Installing the Java 9 Development Kit

Once you have downloaded the correct version of Java for your particular operating system, follow the steps outlined in this section to install the Java 9 JDK . I assume you’ve downloaded Oracle’s Java 9 JDK, but if not, go to following location:

http://www.oracle.com/technetwork/java/javase/downloads/index.html

In the following sections, you will follow steps to install Java 9 on the three popular operating systems: Microsoft Windows, MacOS X, and Linux.

Installing the JDK on Microsoft Windows

The following steps use the Java 9 JDK 64-bit version for the Windows 10 operating system. If your Windows operating system is different, refer to the following link for further details.

http://www.oracle.com/technetwork/java/javase/overview/index.html

The following are steps to install the Java 9 JDK on the Windows OS:

  1. Install the Java 9 JDK by right-clicking the installer’s executable (jdk-9-windows-x64.exe) to run as an administrator. Typically, other operating systems will pop up a similar warning dialog box to alert you of the risks of installing or running binary files. Click the Run button to proceed.

  2. Begin the installation process by clicking on the Next button , as shown in Figure 1-1.

    A323804_3_En_1_Fig1_HTML.jpg
    Figure 1-1. Java SE Development Kit 9 installation process
  3. Next, you’ll be presented with the Custom Setup window allowing you to select optional features shown in Figure 1-2. Here, you’ll just accept the default selections and click the Next button to continue.

    A323804_3_En_1_Fig2_HTML.jpg
    Figure 1-2. Java SE Development Kit 9 optional features
  4. Afterward, the installation process will display a progress bar , as shown in Figure 1-3.

    A323804_3_En_1_Fig3_HTML.jpg
    Figure 1-3. Java SE Development Kit 9 installation in progress
  5. Next, a popup dialog window will ask if you want to change the installation directory of the Java runtime. Just click the Next button and accept the default directory, as shown in Figure 1-4.

    A323804_3_En_1_Fig4_HTML.jpg
    Figure 1-4. The Java 9 runtime destination directory
  6. To complete the installation of the Java 9 SE Development Kit, click the Close button to exit, as shown in Figure 1-5.

    A323804_3_En_1_Fig5_HTML.jpg
    Figure 1-5. The last part of the installation prompting that the Java SE Development Kit 9 was successfully installed

Installing the JDK on MacOS X

The following steps use the Java 9 JDK 64-bit version for the MacOS X (El Capitan) operating system. It assumes you’ve already downloaded the JDK and it’s called something similar to the following:

jdk-9-ea-bin-b88-macosx-x86_64-21_oct_2015.dmg

Use the following steps to install the Java 9 JDK on the MacOS X operating system:

  1. After launching the dmg file, you’ll be presented the following dialog box as shown in Figure 1-6. Next, double-click on the icon to begin the install process.

    A323804_3_En_1_Fig6_HTML.jpg
    Figure 1-6. The Java 9 JDK installer on the MacOS X operating system
  2. Next, to begin the install process shown in Figure 1-7, click on Continue. For the rest of the installation process, accept the defaults.

    A323804_3_En_1_Fig7_HTML.jpg
    Figure 1-7. The Java 9 JDK installer introduction for the MacOS X operating system
  3. After clicking on the Continue button, the dialog will mention the amount of disk space the JDK will take up on your computer, as shown in Figure 1-8. Click on the Install button to proceed .

    A323804_3_En_1_Fig8_HTML.jpg
    Figure 1-8. The prompt showing how much space the JDK will use
  4. For security purposes, your MacOS X will prompt you with a password to allow the installer to continue, as shown in Figure 1-9. This assumes you have admin privileges to install software. After entering your password, click the Install Software button to kick off the process.

    A323804_3_En_1_Fig9_HTML.jpg
    Figure 1-9. The permission window prompting for the username and password that will allow the JDK software to be install on the local machine
  5. The installation process will take a few seconds , as shown in Figure 1-10.

    A323804_3_En_1_Fig10_HTML.jpg
    Figure 1-10. The installation of the JDK in progress
  6. Lastly, you will click on the Close button, as shown in Figure 1-11. This completes the JDK installation on the MacOS operating system.

    A323804_3_En_1_Fig11_HTML.jpg
    Figure 1-11. The installation of the JDK is complete

After finishing the installation of the JDK, you’ll learn later in this chapter how to set up your environment variables. Next are instructions for installing JDK 9 on Linux-based operating systems.

Installing the JDK on Linux

To begin, you should determine if your Linux system is a 32-bit or 64-bit architecture by typing in the following in a terminal:

$ uname -m

The output on a 64 bit Linux machine is as follows:

x86_64

The output on a 32 bit Linux machine is as follows:

i686

Assuming you’ve downloaded the Java JDK at the following:

http://www.oracle.com/technetwork/java/javase/downloads/index.html

For users in the Linux world, you will need to download a file named something like:

  • jdk-9-bin-b88-linux-i586-21_oct_2015.tar.gz

  • jdk-9-bin-b88-linux-i586-21_oct_2015.rpm.

Locate the downloaded file (*.gz or *.rpm) and then go to your terminal window to begin the installation process. The instructions for the installation process are in the next section.

Note

As of the writing of this book, the Java 9 JDK used was an EA (early edition) release and therefore, the JAVA_HOME directory name is subject to change. Visit Java 9 JDK’s installation instructions for further details here: https://docs.oracle.com/javase/9/install/installation-jdk-and-jre-linux-platforms.htm .

Fedora, CentOS, Oracle Linux, or Red Hat Enterprise Linux OSes

After downloading the gz file, you will need to decompress it. On Fedora, CentOS, Oracle Linux, or Red Hat Enterprise Linux OSes , type the following commands to install the JDK.

If a user isn’t registered in the sudoers file, you will need to su as root to perform the following commands.

$ mv ∼/Downloads/jdk-9-linux-x64.tar.gz /tmp
$ cd /tmp
$ tar zxvf /tmp/jdk-9-linux-x64.tar.gz
$ sudo mkdir /opt/jdk/
$ sudo mv jdk-9 /opt/jdk

Use the following command if you downloaded the rpm version of the Java 9 JDK:

$ sudo rpm -ivh jdk-9-linux-x64.rpm

Red Hat Alternatives

After installing JDK 9 your system , you will likely encounter other versions of Java previously installed. Red Hat/CentOS-based operating systems have a way to switch between JDKs and JREs. Since you have installed the JDK 9 in the /opt/jdk directory, you will want alternatives to register the new JDK 9 as the default Java.

To begin let’s register the newly installed Java executable in alternatives. You will want to enter the following commands. These commands will update any indexes, register Java with a priority 100, and display all registered Java runtimes that are installed.

$ sudo update
$ sudo alternatives --install /usr/bin/java java /opt/jdk/jdk-9/bin/java 100

Next, you need to set the default Java version that you just added.

$ sudo alternatives --config java

There are 3 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
  * 1          /opt/jdk/jdk1.8.0_51/bin/java
  + 2          /opt/jdk/jdk1.8.0_66/bin/java
    3          /opt/jdk/jdk-9/bin/java


Enter to keep the current selection[+], or type selection number: 3

To test if alternatives is pointing to the correct version, just type the following in your terminal window:

$ java -version

The following is the output:

java version "1.9.0-ea"
Java(TM) SE Runtime Environment (build 1.9.0-ea-b90)
Java HotSpot(TM) 64-Bit Server VM (build 1.9.0-ea-b90, mixed mode)

You’ll also want to configure alternatives for your javac compiler by performing similar steps as before.

$ sudo alternatives --install /usr/bin/javac javac /opt/jdk/jdk-9/bin/javac 100
$ sudo alternatives --config javac


There are 3 programs which provide 'javac'.

  Selection    Command
-----------------------------------------------
  * 1          /opt/jdk/jdk1.8.0_51/bin/javac
  + 2          /opt/jdk/jdk1.8.0_66/bin/javac
    3          /opt/jdk/jdk-9/bin/javac

To test if alternatives is pointing to the correct Java compiler version , just type the following:

$ javac -version

javac 1.9.0-ea

Ubuntu/Debian

When using you’re Ubuntu or Debian Linux , you can obtain Oracle’s Java JDK in two ways. The first way is to use the apt-get command and the second way is to download the JDK from the official site mentioned earlier.

With Ubuntu or Debian, you can use the apt-get command to download and install Oracle’s official JDK 9:

$ sudo apt-get update
$ sudo apt-get install oracle-java9-installer

After, downloading Linux from Oracle’s download site, you can manually decompress the gz file. For Ubuntu/Debian Linux distributions, pull up your terminal and type the following commands:

$ mv ∼/Downloads/jdk-9-linux-x64.tar.gz /tmp
$ cd /tmp
$ tar zxvf jdk-9-linux-x64.tar.gz
$ sudo mv jdk-9 /usr/lib/jvm/

After installing JDK 9 on your Ubuntu/Debian system , you will likely encounter other versions of Java previously installed. Ubuntu/Debian-based operating systems have a way to switch between JDKs and JREs by using a tool called update-alternatives. Assuming you have installed the JDK 9 using apt-get, it usually puts the JDK in the /usr/lib/jvm directory. Now, you will want alternatives to register the new JDK 9 (java and javac).

Default Java

Type the following to register the new JDK in alternatives:

$ sudo update
$ sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-9-linux-x64/bin/java 100

Next, you’ll want to set the newly registered java as the default version to use. Type in the following commands:

$ sudo update-alternatives --config java

There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                      Priority   Status
-----------------------------------------------------------------------------
* 0            /usr/lib/jvm/java-8-openjdk/jre/bin/java  1061       auto mode
  1            /usr/lib/jvm/java-9-oracle/bin/java       100        manual mode


Press enter to keep the current choice[*], or type selection number: 1

$ sudo update-alternatives --display java

  Selection    Path                                       Priority   Status
-----------------------------------------------------------------------------
  0            /usr/lib/jvm/java-8-openjdk/jre/bin/java   1061       auto mode
* 1            /usr/lib/jvm/java-9-oracle/bin/java        100        manual mode
Default Javac

You’ll also want to switch the javac compiler too. To set the Java compiler, type the following commands to register the new javac:

$ sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-9-linux-x64/bin/javac 100
$ sudo update-alternatives --config javac


There are 2 choices for the alternative javac (providing /usr/bin/javac).

  Selection    Path                                    Priority   Status
-----------------------------------------------------------------------------
* 0            /usr/lib/jvm/java-8-openjdk/bin/javac   1061       auto mode
  1            /usr/lib/jvm/java-9-oracle/bin/javac    100        manual mode


Press enter to keep the current choice[*], or type selection number: 1

$ sudo update-alternatives --config javac

There are 2 choices for the alternative javac (providing /usr/bin/javac).

  Selection    Path                                    Priority   Status
-----------------------------------------------------------------------------
  0            /usr/lib/jvm/java-8-openjdk/bin/javac   1061       auto mode
* 1            /usr/lib/jvm/java-9-oracle/bin/javac    100        manual mode

Setting Environment Variables

If you aren’t using the conveniences of aternatives to point to your default Java binaries, you can do it the old fashioned way, by setting up Java environment variables. There are other strategies to easily switch Java versions that I’ve not mentioned in this chapter, but understanding Java’s environmental variables will allow you to install and develop Java applications on any operating system.

To get started you need to set and update a couple of important environment variables. How you set them and the values they should be set to vary depending on your choice of operating system. The two variables to set are the following:

  • JAVA_HOME: Tells your operating system where the Java installation directory lives.

  • PATH: Specifies where the Java executable directory resides. This environment variable lets the system search paths or directories containing executable files. Java executables reside in the bin directory under the JAVA_HOME home directory.

The following are the environment variables to set in the 32-bit Windows operating system:

set JAVA_HOME="C:Program Files (x86)Javajdk-9"
set PATH=%JAVA_HOME%in;%PATH%

Set the same variables in 64-bit Windows, but the values are slightly different:

set JAVA_HOME="C:Program FilesJavajdk-9"
set PATH=%JAVA_HOME%in;%PATH%
Note

Depending on the version of the JDK the JAVA_HOME path, the name will change according to the version that was installed. For example, if the next version is named JDK 9.0.1, the path would likely appear as JAVA_HOME="C:Program FilesJavajdk-9.0.1". To see Java 9’s JDK and JRE version naming scheme, go to the following links:

http://openjdk.java.net/jeps/223 and

https://blogs.oracle.com/java-platform-group/a-new-jdk-9-version-string-scheme .

On Unix-like platforms such as MacOS X and Linux, your settings and how you make them depend on which shell you are using. The following examples show you how to set the needed variables for Bash, Bourne, and CSH shells, respectively.

# Mac OS X /bin/bash
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
export PATH=$PATH:$JAVA_HOME/bin


# Linux bash, bourne shell environments /bin/bash
export JAVA_HOME=/usr/java/jdk-9 export PATH=$PATH:$JAVA_HOME/bin


#csh environments /bin/csh
setenv JAVA_HOME /usr/java/jdk-9
setenv PATH ${JAVA_HOME}/bin:${PATH}

These statements will set environment variables temporarily for the current terminal window session. To make JAVA_HOME and PATH more permanent, you will want to add them to your system upon logon such 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.

Setup Windows Environment Variables

In the Windows environment you can use the keyboard shortcut Windows logo key+Pause/Break key, and then click the Advanced system settings (link on the left side) to display the Systems Properties window, as shown in Figure 1-12.

A323804_3_En_1_Fig12_HTML.jpg
Figure 1-12. The System Properties window

Next, click the Environment Variables button . At this point 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. The Environment Variables window on the Windows operating system is shown in Figure 1-13.

A323804_3_En_1_Fig13_HTML.jpg
Figure 1-13. Windows Environment Variables window

To add the JAVA_HOME environment variable, click on the New button shown in Figure 1-13.

After you click the New button, the window in Figure 1-14 appears and allows you to enter the environment variable name and value . When you’re done, click on the OK button.

A323804_3_En_1_Fig14_HTML.jpg
Figure 1-14. The Add/Edit window to enter the JAVA_HOME environment variable

After, you’ve clicked on OK to add JAVA_HOME, you will need update the Path environment variable, as shown in Figure 1-15. Select the Path environment variable in the System Variables area. Next, click on the Edit button.

A323804_3_En_1_Fig15_HTML.jpg
Figure 1-15. Editing the Path environment variable

In Windows 10, you need to edit the Path environment variable by adding an new entry, as shown in Figure 1-16. Here you will add an entry such as %JAVA_HOME%in. To add the entry, click on the New button. If the entry already exists , click on the Edit button. This allows the system to see all binary executables in the bin directory of the JAVA_HOME. In other words, when you are on the terminal or command-line prompt, the system will recognize files such as javac.exe for the Java compiler.

A323804_3_En_1_Fig16_HTML.jpg
Figure 1-16. Adding %JAVA_HOME%in to the Path environment variable

In Figure 1-16, the %JAVA_HOME%in entry was at the bottom of the list, but I moved it to the top by clicking on the Move Up button .

Setting Up MacOS X/Linux Environment Variables

To make the environment variables permanent on MacOS X or Linux , you can use common text editors such as nano or vim. But before you go editing your user shell profile files, you will want to make a backup copy just in case you make a mistake. Because many Unix and Linux systems have different shells, I’ve detailed the typical files to copy and edit.

On a Mac, type the following:

$ cp ∼/.bash_profile ∼/.bash_profile.orig

On a Linux OS, you’ll type the following to determine the kind of shell you have, then you’ll know which file to copy and edit. Different shells use different files to export environment variables when creating a console session .

$  echo $0
-bash

If the output displays -bash, you’ll want to back up and edit the .bashrc file from your home directory. If the output displays -csh, you’ll want to back up and edit the .cshrc from your home directory. Next, you copy the .bashrc file as a backup before editing it.

$ cp ∼/.bashrc ∼/.bashrc.orig

If you’re on a Linux OS using the C shell, type the following:

$ cp ∼/.cshrc ∼/.cshrc.orig

Now, you’ll want to edit the file that you just backed up by using nano or vi text editor. To load a file, you type the following:

$ nano ∼/.bash_profile

Or

$ vi ∼/.bash_profile

Notice that I used the ∼/.bash_profile file located in the home directory on the MacOS X operating system. I trust you will replace the file with the particular file depending on your Linux OS and shell. After loading the file from the previous command you will want to perform edits, saves, and exits from those editors. Tables 1-1 and 1-2 are quick run-downs of the common commands for nano and vim, respectively.

Table 1-1. The Nano Editor’s Keyboard Commands After Editing a File

Action

Command

Notes

Navigate

Use arrow keys up, down, right, and left

Arrow keys, Page Up/Down, and Home and End can also be used to navigate the cursor.

Save File

Ctrl/Control+O

Editor prompts the name of the file. Just press Enter to accept the same name.

Exit Editor

Ctrl/Control+X

Brings you back to the command-line prompt .

Table 1-2. The vi Editor’s Keyboard Commands After Editing a File

Action

Command

Notes

Navigate

Use arrow keys up, down, right, and left

Arrow keys, Page Up/Down, and Home and End can also be used to navigate cursor.

Insert text

i

After a text file is loaded you can modify the file, but before you can, you have to press ‘i’ for insert. To get back to command mode, press the ESC key.

Add text

a

After a text file is loaded you can modify the file, but before you can you have to press ‘a’ for add. To get back to command mode, press the ESC key.

Command mode

ESC

Exits editor mode, bringing you to command mode.

Save file

:w <Enter key>

Assuming you are in command mode (press ESC) before typing :w (colon ‘w’). The file is saved. To save and exit, type :wq.

Exit editor

:q

Brings you back to the command-line prompt.

Exit with no changes

:q!

Modifications are ignored and exits editor .

Save and Exit

:wq

File is saved and exits immediately.

  • To set your JAVA_HOME for the MacOS X platform, you need to launch a terminal window to edit your home directory’s .bash_profile file (for example , nano ∼/.bash_profile) by adding the export commands at the bottom of the file:

    # Mac OS X /bin/bash
    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
    export PATH=$PATH:$JAVA_HOME/bin
  • 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. Add the export commands.

    # Linux bash, bourne shell environments /bin/bash
    export JAVA_HOME=/usr/java/jdk-9
    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. Add the export commands.

    #csh environments
    setenv JAVA_HOME /usr/java/jdk-9
    setenv PATH ${JAVA_HOME}/bin:${PATH}

Once you’ve set up your path and JAVA_HOME environment variables , you will want to verify them by launching a terminal window and executing the following two commands from the command prompt:

$ java -version
$ javac -version

The output in each case should display a message indicating the Java 9 version of the language and runtime. Here is the display output of the version.

Java -version

java version "1.9.0-ea"
Java(TM) SE Runtime Environment (build 1.9.0-ea-b90)
Java HotSpot(TM) 64-Bit Server VM (build 1.9.0-ea-b90, mixed mode)


javac -version

javac 1.9.0

Installing Gradle

If you have not downloaded Gradle yet, visit http://gradle.org/gradle-download . After downloading the binary distribution, you’ll want to install Gradle. To install Gradle, follow these steps:

  1. Unzip the Gradle software into a directory.

  2. Update the environment variable GRADLE_HOME to point to the directory located where the gradle folder was created after the unzipped file.

  3. Update the environment variable PATH to include the $GRADLE_HOME/bin. In Windows, it would be %GRADLE_HOME%/bin. To make these variables permanent, follow the instructions mentioned earlier regarding JAVA_HOME.

  4. To verify that Gradle was installed properly at the command line (the terminal), type the following command :

    gradle -version

The version information is shown here:

------------------------------------------------------------
Gradle 2.7
------------------------------------------------------------


Build time:   2015-09-14 07:26:16 UTC
Build number: none
Revision:     c41505168da69fb0650f4e31c9e01b50ffc97893


Groovy:       2.3.10
Ant:          Apache Ant(TM) version 1.9.3 compiled on December 23 2013
JVM:          1.9.0-ea (Oracle Corporation 1.9.0-ea-b90)
OS:           Mac OS X 10.11.1 x86_64

Now that you have the JDK installed, you can install the NetBeans IDE. Installing the NetBeans IDE is optional, so you may skip the next section.

Installing the NetBeans IDE

When developing JavaFX applications, you might want to use the NetBeans IDE. Be sure to download the correct NetBeans version containing JavaFX. If you haven’t already downloaded the NetBeans IDE, go to following location:

https://netbeans.org/downloads/index.html

To install the NetBeans IDE, follow these steps:

  1. Install NetBeans 8.2 or later. Launch the binary executable. On the Windows platform, you will receive a security warning to inform the user about installing software.

  2. Begin the NetBeans IDE installation process by clicking the Next button . Figure 1-17 prompts the user to begin the installation process.

    A323804_3_En_1_Fig17_HTML.jpg
    Figure 1-17. NetBeans IDE installer
  3. Read and accept the NetBeans license agreement . After reading and agreeing to the terms, click the “I accept the terms in the license agreement” check box and then click Next to proceed as shown in Figure 1-18.

    A323804_3_En_1_Fig18_HTML.jpg
    Figure 1-18. NetBeans license agreement
  4. Next, you can choose the destination directory to install NetBeans and select the Java 9 SE Development Kit previously installed. As usual, keep the defaults for the destination to install the NetBeans IDE and the JDK 9, as shown in Figure 1-19.

    A323804_3_En_1_Fig19_HTML.jpg
    Figure 1-19. NetBeans IDE installation
  5. On the Summary screen, the Check for Updates option allows the installer to retrieve any updates or patches to the current NetBeans version and any other plug-in dependencies. Accept the defaults and click the Install button, as shown in Figure 1-20.

    A323804_3_En_1_Fig20_HTML.jpg
    Figure 1-20. Check for updates

    Figure 1-21 shows the installation progress bar .

    A323804_3_En_1_Fig21_HTML.jpg
    Figure 1-21. Installation progress
  6. To complete the setup, in Figure 1-22 you will be prompted for an optional check box to Contribute to the NetBeans team to provide anonymous data usage to help diagnose issues and enhance the product. Once you have decided whether to contribute, click the Finish button to complete the installation.

    A323804_3_En_1_Fig22_HTML.jpg
    Figure 1-22. Setup complete
  7. Launch the NetBeans IDE to see the opening page , as shown in Figure 1-23.

    A323804_3_En_1_Fig23_HTML.jpg
    Figure 1-23. NetBeans start page

Now you are ready to go forward and create awesome JavaFX applications!

Creating a JavaFX HelloWorld Application

When creating JavaFX applications, you’ll be learning three ways to develop, compile, and run applications.

  • NetBeans IDE

  • Editor and terminal (the command-line prompt)

  • Editor and the Gradle Build tool

Using the NetBeans IDE

To quickly get started with creating, coding, compiling, and running a simple JavaFX HelloWorld application using the NetBeans IDE, follow the steps outlined in this section. You’ll want to go deeper in the next section to get an understanding of what the IDE is doing behind the scenes on your behalf. For now, though, let’s just get some code written and running.

  1. Launch NetBeans IDE.

  2. On the File menu, select File ➤ New Project.

  3. Under Choose Project and Categories , select the JavaFX folder.

  4. Under Projects, select Java FX Application, and click Next.

  5. Specify HelloWorld for your project name.

  6. Change or accept the defaults for the Project Location and Project Folder fields . Figure 1-24 shows the New JavaFX Application wizard used to create a simple HelloWorld application.

    A323804_3_En_1_Fig24_HTML.jpg
    Figure 1-24. New JavaFX Application wizard
  7. On this screen (Figure 1-24), click the Manage Platforms button to make sure the Platform Name field contains JDK 1.9 or greater as the default. Click Finish to auto-create the JavaFX HelloWorld application.

  8. In a few seconds, NetBeans will generate all the necessary files for the HelloWorld project. After NetBeans finishes, the project will show up on the left Projects tab. Figure 1-25 shows a newly created HelloWorld project .

    A323804_3_En_1_Fig25_HTML.jpg
    Figure 1-25. A newly created HelloWorld project
  9. In the NetBeans IDE on the Projects tab (left), select the newly created project. Open the Project Properties dialog box from the File menu option Project Properties. Here you will verify that the Source/Binary format setting is using JDK 9, as shown in Figure 1-26. Click Sources under Categories.

    A323804_3_En_1_Fig26_HTML.jpg
    Figure 1-26. Project properties
  10. To run and test your JavaFX HelloWorld application, ensure the project folder is selected (the left Projects tab), then click on the green Run button or press the F6 key to execute the HelloWorld project. Figure 1-27 shows the Run Project option used to launch the JavaFX application.

    A323804_3_En_1_Fig27_HTML.jpg
    Figure 1-27. Running the HelloWorld project
  11. After you choose the Run option, the output should look like Figure 1-28.

    A323804_3_En_1_Fig28_HTML.jpg
    Figure 1-28. JavaFX HelloWorld launched from the NetBeans IDE

You shouldn’t encounter any difficulty when following Steps 1 through 8. However, steps 9 ensures that your project’s source/binary format is using JDK 9. Because of the new additions to the Java language in Java 9, such as modules, some of the source code in this book will rely on the new syntax and therefore will not be backward-compatible with prior versions of Java 9. Typically, developers have prior versions of the Java development kit such as JDK 8. NetBeans allows you to switch between different JDKs when projects require older versions. An important thing to note is that in early releases of JavaFX 2.0, the software was packaged separately from the Java SDK, which caused some software versioning confusion. Thank goodness it is now just one download (JDK 9)! If you are still using Java 7 SDK, the latest download will also contain JavaFX in one bundle since JavaFX 2.1.

Note

Did you know that Java 7 is at the end of its life? This means that Oracle will no longer post any updates or releases for the public. Unless you still have a commercial license and a support contract with Oracle, it is advised you migrate applications to Java 8 or later. Having no updates to Java 7’s runtime may be a security concern. So, you’ve been warned. The official Java 7 end of life and FAQ site is here: https://www.java.com/en/download/faq/java_7.xml .

Using an Editor and the Terminal (the Command-Line Prompt )

The second way of developing JavaFX 9 applications is to use a common text editor and the command-line prompt (terminal). By learning how to compile and execute applications on the command-line prompt, you will learn about the classpath and where the executable files reside. Being exposed to this will sharpen your skills when you are in environments where fancy IDEs and/or editors aren’t easily available.

Working from the command line, you will basically use a text editor such as nano, vi, Emacs, or Notepad to code your JavaFX HelloWorld source. The example shown in Listing 1-1 is of a HelloWorld Java application.

Listing 1-1. A JavaFX HelloWorld Application from HelloWorld.java
package org.acme.helloworld;

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


/**
 * A JavaFX Hello World Application
 */
public class HelloWorld extends Application {


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Application.launch(args);
    }


    @Override
    public void start(Stage stage) {
        stage.setTitle("Hello World");
        Group root = new Group();
        Scene scene = new Scene(root, 300, 250);
        Button btn = new Button();
        btn.setLayoutX(100);
        btn.setLayoutY(80);
        btn.setText("Hello World");
        btn.setOnAction(new EventHandler<ActionEvent>() {


            public void handle(ActionEvent event) {
                System.out.println("Hello World");
            }
        });
        root.getChildren().add(btn);
        stage.setScene(scene);
        stage.show();
    }
}

Once the Java file is created you will use the command-line prompt or terminal window to compile and run your JavaFX application. The following are steps to create a JavaFX HelloWorld application to be compiled and run on the command-line prompt (terminal).

  1. In your user home directory, make a projects directory and underneath it you will create a helloworld directory.

    On a MacOS or Linux operating system, use the following command to make a projects directory:

    $ mkdir -p ∼/projects/helloworld/src
    $ mkdir ∼/projects/helloworld/classes
    $ cd ∼/projects/helloworld/
    $ nano src/HelloWorld.java

    On a Windows operating system, use the following command to change directories:

    C:Usersmyusername>mkdir projects
    C:Usersmyusername>mkdir projectshelloworld
    C:Usersmyusername>mkdir projectshelloworldsrc
    C:Usersmyusername>mkdir projectshelloworldclasses
    C:Usersmyusername>cd projectshelloworld
    C:Usersmyusernameprojectshelloworld>notepad srcHelloWorld.java
  2. Copy and paste the code from Listing 1-1 into a text editor and save the file as HelloWorld.java. The file should reside inside the src directory.

    Note When entering the code for the HelloWorld.java file from Listing 1-1, be sure to include the package org.acme.helloworld; statement at the top. By doing so, the package namespace directories are created when the code is compiled. For example, the compiled HelloWorld.class file will reside in the classes/org/acme/helloworld directory.

  3. Compile the source code file called HelloWorld.java using the Java compiler javac with the -d switch and the classes directory. The classes directory is where the compiled code goes. Also, you need to specify the source code files to compile, which is src/*.java. The commands you need to enter depend on your operating system.

    On a MacOS X or Linux operating system, type the following on the command-line prompt:

    $ javac -d classes src/*.java

    On a Windows command line, type the following:

    C:Usersmyusernameprojectshelloworld> javac -d classes src*.java

    Notice the -d classes before the filename. The -d option (destination directory) lets the Java compiler know where to put the compiled class files based on their package namespace. In this scenario, the HelloWorld package statement (namespace) is org.acme.helloworld, which will create subdirectories under the classes directory, assuming you are in the ∼/projects/helloworld project directory.

    When you’re finished compiling, your directory structure should resemble Figure 1-29.

    A323804_3_En_1_Fig29_HTML.jpg
    Figure 1-29. The compiled HelloWorld example creates directories based on the package namespace under the classes directory. You will notice the subdirectories are created as org/acme/helloworld under the classes directory you created earlier.
  4. Run and test your JavaFX HelloWorld application . Assuming you are in the ∼/projects/helloworld directory, type the following command to run your JavaFX HelloWorld application from the command-line prompt:

    $ java -cp classes org.acme.helloworld.HelloWorld

On Windows OS:

C:Usersmyusernameprojectshelloworld> java -cp classes org.acme.helloworld.HelloWorld

By using the -cp, classes will let Java know where the classpath directory is located. Figure 1-30 shows the output of a simple JavaFX HelloWorld application launched from the command-line prompt .

A323804_3_En_1_Fig30_HTML.jpg
Figure 1-30. JavaFX HelloWorld launched from the MacOS X command-line prompt

Using Gradle on the Command-Line Prompt

A third way of developing JavaFX applications is using the Gradle Build tool. Here you will be also using a common text editor like before, but instead of manual steps in creating and compiling code, you will be relying on the Gradle Build tool. If you have not set up Gradle, refer to the early part of this chapter in the section entitled “Installing Gradle.” Follow these steps to create a Gradle-based project .

  1. Create another project and directory named helloworld_gradle. Assuming you are in the ∼/projects directory, you will create a Gradle-based project.

    On a Unix-like OS, enter the following:

    $ mkdir -p projectshelloworld_gradle

    On Windows, enter the following:

    C:Usersmyusername>mkdir projectshelloworld_gradle
  2. Change your directory to the helloworld_gradle.

    On a Unix-like OS, enter the following:

    $ cd helloworld_gradle

    On Windows, enter the following:

    C:Usersmyusername>cd projectshelloworld_gradle
  3. Build a Java skeleton project having the conventional directory structure (Maven and Gradle convention). You will notice directories created that will look like src/main/java and src/test/java. Since this creates the project files and directories initially, it should only be done once. The following command creates a Java library project:

    $ gradle init --type java-library

    The following is the output when executing the Gradle init task:

    :wrapper
    :init


    BUILD SUCCESSFUL

    Total time: 1.897 secs
  4. Since you are creating a JavaFX application and not a Java library, you will remove the Library.java and LibraryTest.java files under the src/main/java and src/test/java directories , respectively. These files are just stubbed out to get you started if you decide to create a Java library. In this scenario, you are creating a JavaFX application.

  5. Next, you’ll create a directory called org/acme/helloworld under the src/main/java directory and copy the HelloWorld.java file from Listing 1-1 into the src/main/java/org/acme/helloworld directory. This will look like Figure 1-31.

    A323804_3_En_1_Fig31_HTML.jpg
    Figure 1-31. Gradle Java application project structure. Notice the standard convention of source code directory structure laid out as src/main/java and src/test/java. Build tools such as Maven and Gradle follow this convention.
  6. Since you are creating a JavaFX application, you will need to edit the build.gradle file by adding a plug-in that will build the Java project as a launchable application. You’ll also add one more entry to let Gradle know which class the main application should be run as. Using your text editor, add the following entries to the build.gradle file:

    apply plugin: 'application'

    mainClassName = "org.acme.helloworld.HelloWorld"
  7. After you’ve saved and exited the file, you’ll want to build the project using the gradle assemble command. This will create an executable jar file that can be run. Type the following to compile and build a HelloWorld jar executable.

    $ gradle assemble

    The following is the output after executing the Gradle assemble task.

    :compileJava
    Download https://jcenter.bintray.com/org/slf4j/slf4j-api/1.7.12/slf4j-api-1.7.12.pom
    Download https://jcenter.bintray.com/org/slf4j/slf4j-parent/1.7.12/slf4j-parent-1.7.12.pom
    Download https://jcenter.bintray.com/org/slf4j/slf4j-api/1.7.12/slf4j-api-1.7.12.jar
    :processResources UP-TO-DATE
    :classes
    :jar
    :assemble


    BUILD SUCCESSFUL

    Total time: 4.458 secs
  8. Now run the HelloWorld application by using the following command (run task).

    $ gradle run
  9. The Gradle run task was added when you added the plug-in entry apply plugin: 'application'. Gradle plug-ins provide convenient ways to build different kinds of Java projects and artifacts. You should see the Java HelloWorld application launch just like in Figure 1-30.

There are many more powerful things you can do with Gradle that are beyond the scope of this book; however, I will list some common commands you might be interested in using.

  • gradle tasks: Lists all the available tasks

  • gradle clean: Removes directories and files from the build directory

  • gradle eclipseProject: Creates project files for the Eclipse IDE. This task will be available when you add the following statement to the build.gradle file:

    apply plugin: 'eclipse'
  • gradle intellijProject: Creates project files for the IntelliJ IDE. This task will be available when you add the following statement to the build.gradle file:

    apply plugin: 'idea'
  • gradle -help: Shows the available options and descriptions of commands

Walking Through the HelloWorld Source Code

You’ll notice in the source code that JavaFX-based applications extend (inherit) from the javafx.application.Application class. The Application class provides application lifecycle functions such as initializing, launching, starting, and stopping during runtime. This provides a mechanism for Java applications to launch JavaFX GUI components separate from the main thread. The code in Listing 1-2 is a skeleton of the JavaFX HelloWorld application, having a main() method and an overridden start() method.

Listing 1-2. A Skeleton Version of the HelloWorld.java File
public class HelloWorld extends Application {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // On the main thread
        Application.launch(args);
    }


    @Override
    public void start(Stage stage) {
        // On the JavaFX application thread


        // JavaFX code goes here...
    }
}

Here, in the main() method’s entry point, you launch the JavaFX application by simply passing in the command-line arguments to the Application.launch() method. To access any arguments passed into the launch() method, you can invoke the getParameters() method of the Application class. See the Javadoc documentation for details on various ways to access named and raw arguments. The following link is the Javadoc documentation for the getParameters() method:

https://docs.oracle.com/javase/8/javafx/api/javafx/application/Application.html#getParameters--

After the Application.launch() method has executed, the application will enter a ready state, and the framework internals will invoke the start() method to begin. 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 the developer to use and manipulate. Following is the overridden Application start() method:

@Override
public void start(Stage stage) {...}

When the program begins in the start() method , a separate thread of execution occurs, called the JavaFX application thread. Keep in mind that running on the JavaFX application thread is synonymous in concept with running on Java Swing’s event dispatch thread. Just be advised the difference between the Java main thread and the UI thread when it relates to UI applications. Later in this book, you will learn how to create background processes to avoid blocking the JavaFX application thread. When you know how to build applications to avoid blocking the GUI, the user will notice that your application is much more responsive (snappy) under heavy usage. Mastering responsiveness in GUI applications is an important concept in enhancing usability and the overall user experience. To see the Java Application API, visit the Javadoc here:

https://docs.oracle.com/javase/8/javafx/api/javafx/application/Application.html

https://docs.oracle.com/javase/9/

JavaFX Scene Graph

You’ll notice that some classes and objects are oddly named, such as Stage and Scene. There isn’t a coincidence—the designers of the API have modeled things after the idea of a theater or a play in which actors perform in front of an audience. In this analogy, a play consists of one-to-many scenes in which actors perform. And, of course, all scenes are performed on a stage one at a time. In JavaFX, the Stage is equivalent to an application window similar to Java Swing API JFrame or JDialog on the desktop. Depending on the device, such as a Raspberry Pi (Raspbian), there may be only one stage. You can think of a Scene object as a content pane, similar to Java Swing’s JPanel, capable of holding zero-to-many Node objects (children).

Proceeding with the example, in the start() method, you see that for a JavaFX desktop window (stage) you can set the title bar using the setTitle() method. Next, you create a root node (Group), which is added to the Scene object as the top-level surface for the application window. The following code snippet shows you how to set the title and create the scene:

stage.setTitle("Hello World");
Group root = new Group();
Scene scene = new Scene(root, 300, 250);

JavaFX Node

A JavaFX node is a fundamental base class for all scene graph nodes to be rendered. The following graphics capabilities can be applied to nodes: scaling, transforms, translations, and effects.

Some of the most commonly used nodes are UI controls and Shape objects. Similar to a tree data structure, a scene graph will contain children nodes by using a container class such as the Group or Pane class. You’ll learn more about the Group class later when you look at the ObservableList class, but for now you can think of them as Java List or Collection classes that are capable of holding child node objects. In the following code, a button (Button) node is created to be positioned on the scene and set with an event handler (EventHandler<ActionEvent>), which responds when the user presses the button. The handler code will output the text "Hello World" on the console. For now the code shown here uses an anonymous inner class; however you will learn later in Chapter 3 to use lambda expressions introduced in Java 8.

Button btn = new Button();
btn.setLayoutX(100);
btn.setLayoutY(80);
btn.setText("Hello World");
btn.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent event) {
       System.out.println("Hello World");
    }
});
root.getChildren().add(btn);

Once the child nodes have been added to the root Group via the getChildren().add() method, you set the stage’s scene and call the show() method on the Stage object to display a JavaFX application window. By default, the window will allow users to minimize, maximize, and close (exit) the application. The following code sets the scene and displays the JavaFX application window (the Stage):

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

Packaging a JavaFX Application

At some point you will want to distribute or deploy your JavaFX application. To handle the numerous application packaging and deployment strategies, Oracle’s Java team has created a Java Packager tool to assist developers in building, packaging, and deploying their applications. To learn more about how to use Java Packager tool, see Oracle’s “Deploying JavaFX Applications” at the following URL:

https://docs.oracle.com/javase/8/docs/technotes/tools/unix/javapackager.html

To give you a taste of the Java Packager tool's capabilities, I will show you how to package the HelloWorld classes into a single executable file for the many supported platforms. This will allow users to double-click to launch or install the application on the native operating system. The following commands will automatically compile and generate executables, launchers, and installers located in ∼/projects/helloworld/dist/bundles directory. Type the following to create deployable Java applications.

$ cd ∼/projects/helloworld
$ javapackager -makeall -appclass org.acme.helloworld.HelloWorld -name hellothere

Table 1-3 describes the common options and switches that are used in building distributable JavaFX executable application bundles.

Table 1-3. Common JavaPackager Options to Build an Executable jar

Option/Switch

Example

Description

-createjar

--

Creates a JavaFX jar executable application.

-appclass

org.acme.helloworld.HelloWorld

Specifies the fully qualified name of the class containing the main() method.

-srcdir

.

The top-level location of the parent directory holding the compiled classes (current directory).

-outdir

out

The destination where the packaged jar file will be created.

-outfile

helloworld.jar

Specifies the name of the executable jar file.

-v

--

Allows verbose displays logging information when executing javapackager.

-native

dmg

JavaPackager can create installer, image, exe, msi, dmg, rpm, and deb file extensions as deployable executables on the native OS platform.

-makeall

 

Based on the OS the packager tool will build installers and executables. For example, for the MacOS X platform, the dist/bundle directory will contain executables with file extensions of the following: jnlp, dmg, app, pkg, and jar.

To run the jar executable on the command line, you simply type the following and press Enter:

$ java -jar dist/bundles/dist.jar

To launch HelloWorld as a standalone application on the MacOS X operating system, just double-click on the hellothere-1.0.dmg or hellothere-1.0.pkg application file in the bundles directory, as shown in Figure 1-32.

A323804_3_En_1_Fig32_HTML.jpg
Figure 1-32. Java Packager creates executables and installers of the HelloWorld application named hellothere. Other application bundles exist, such as hellothere-1.0.dmg, to install the application correctly on the MacOS X desktop.

There are many ways to package and deploy JavaFX applications. To learn more, see Oracle’s “Java Packager Guide” at the following URL:

https://docs.oracle.com/javase/8/docs/technotes/tools/unix/javapackager.html

Also see the following, related articles:

Downloading the Book’s Source Code

To get the source code for the book’s examples, you can go to two places:

Summary

So far you have managed to download and install Java 9 JDK, Gradle, and NetBeans IDE. After successfully installing the prerequisite software, you created a JavaFX HelloWorld GUI application through the NetBeans IDE . Then you were able to use a text editor to enter your source code and eventually compile and run the binary class via a command-line prompt (the terminal window). Another method you learned was the use of the Gradle Build tool to compile and launch the JavaFX application using tasks.

After learning three methods for compiling, building, and running a JavaFX application, you went through a quick code walkthrough of the HelloWorld.java source file. You also learned to package a JavaFX application as a standalone jar, dmg, pkg, and jnlp executable using the JavaFX Packager tool. Lastly, you learned that you have two places to obtain the source code for the book.

Next, in Chapter 2, you learn what’s new in JDK 9 regarding project Jigsaw. If you understand JDK 9’s modularity and are impatient, you can go to Chapter 3 to learn the fundamentals of JavaFX 9, such as drawing and coloring shapes as well as drawing text and changing text fonts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.159.25