Getting Started
To get started using this book to learn JavaFX 8, 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 “Hello World” example. Once you are comfortable with the development environment, we will walk through the JavaFX Hello World 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 provided two methods to compile and run the Hello World example. In the first method you will be using the Netbeans IDE and in the second method you will learn how to use the command line (terminal window) to compile and launch JavaFX applications. The second method is an approach for those who are not fond of fancy IDEs.
If you are already familiar with the installation of the Java Development Kit (JDK) and the NetBeans IDE, you can skip to Chapter 2, which covers the fundamentals (JavaFX 2D). Let’s get started!
When using this book you’ll need to download and install Java 8 Java Development Kit (JDK) or a later version. Get it from the following URL:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Also install NetBeans 8 or greater:
https://netbeans.org/downloads
Currently JavaFX 8 runs on the following operating systems:
After downloading the appropriate software versions for your operating system, you will install the Java 8 JDK and the NetBeans 8 IDE.
Installing the Java 8 Development Kit
The first thing to do is install the correct version of Java. You want the development kit, not the runtime. Follow the steps outlined in this section to download and install Java 8. Download the Java 8 JDK from the following location:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
In the following steps I will be using the Java 8 JDK 32-bit version for the Windows 7 operating system as an example. The steps are similar on other operating systems and JDK versions; however, if your environment is different, please refer to http://www.oracle.com/technetwork/java/javase/overview/index.html for additional details. The following are steps to install the Java 8 JDK:
Figure 1-1. The Windows Security Warning dialog window
Figure 1-2. Java SE Development Kit 8 setup
Figure 1-3. Java SE Development Kit 8 optional features
Figure 1-4. Java SE Development Kit 8 installation in progress
Figure 1-5. The Java 8 runtime destination directory
Figure 1-6. Java 8 runtime destination directory
Now you need to set a couple of key 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:
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.
Following are the variables to set in 32-bit Windows:
set JAVA_HOME="C:Program Files (x86)Javajdk1.8.0"
set PATH=%JAVA_HOME%in;%PATH%
Set the same variables in 64-bit Windows, but the values are different:
set JAVA_HOME="C:Program FilesJavajdk1.8.0"
set PATH=%JAVA_HOME%in;%PATH%
On Unix-based platforms such as Mac OS X and Linux, your settings and how you make them depend somewhat upon which shell you are using. The following examples show how to set the needed variables for the Bash and Bourne, and the CSH shells:
# bash, bourne shell environments
export JAVA_HOME=/usr/java/jdk1.8.0
export PATH=$PATH:$JAVA_HOME/bin
#csh environments
setenv JAVA_HOME /usr/java/jdk1.8.0
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 login. 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 the Advanced system settings to display the Systems Property dialog.
Next, click 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 Figure 1-7 is the Environment Variables dialog on the Windows operating system.
Figure 1-7. Windows Environment Variables
Once you’ve set up your path and JAVA_HOME environment variables, you will want to verify 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 8 version of the language and runtime.
When developing JavaFX applications you will be using the NetBeans IDE. Be sure to download the correct NetBeans version containing JavaFX. To install the NetBeans IDE, follow these steps:
https://netbeans.org/downloads/index.html
Figure 1-8. Windows security warning
Figure 1-9. NetBeans IDE installer
Figure 1-10. NetBeans license agreement
Figure 1-11. JUnit license agreement
Figure 1-12. NetBeans IDE installation
Figure 1-13. NetBeans IDE installation selecting JDK 8
Figure 1-14. Check for Updates
Shown in Figure 1-15 is the installation progress bar.
Figure 1-15. Installation progress
Figure 1-16. Setup complete
Figure 1-17. NetBeans start page
Now you are ready to go forward and create JavaFX applications.
Creating a JavaFX Hello World Application
You’ll be learning two methods in this section to develop, compile, and run a JavaFX-based HelloWorld application. In the first method you will be using the NetBeans IDE we just installed and in the second method you will develop a JavaFX application without using an IDE.
To quickly get started with creating, coding, compiling, and running a simple JavaFX HelloWorld application using the NetBeans IDE, follow the steps outline 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.
Figure 1-18. New JavaFX Application wizard
Figure 1-19. The Java Platform Manager window containing JDK 1.8 as a managed platform
Figure 1-20. A newly created HelloWorld project
Note In the NetBeans IDE, which may have other projects, you may encounter a particular project set as the main project. It is advised to set the main project as None by choosing Run Set Main Project select None (as shown in Figure 1-22). By doing this it allows a project to run just by clicking on the green arrowed button. Assuming the project is selected on the left in the Projects tab. NetBeans will automatically search a project’s JavaFX main application class to launch the application. See step 10, following.
Figure 1-21. Project Properties
Figure 1-22. Setting the HelloWorld project as the Main Project
Figure 1-23. JavaFX Hello World 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 8. Because of the new additions to the Java language in Java 8, such as lambdas, most 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 8. Typically, developers have prior versions of the Java development kit such as JDK 7. 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 8)! If you are still using Java 7 SDK, the latest download will also contain JavaFX in one bundle since JavaFX 2.1.
The second method of developing JavaFX 8 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. This exposure should 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 popular text editors such as vi, Emacs, or Notepad to code your JavaFX Hello World application. An example is shown in Listing 1-1.
Listing 1-1. A JavaFX Hello World application from HelloWorldMain.java
package helloworldmain;
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
* @author carldea
*/
public class HelloWorldMain extends Application {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.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);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Once the Java file is created you will use the command-line prompt or terminal window to compile and run your JavaFX application. Following are the steps to create a JavaFX Hello World application to be compiled and run on the command-line prompt.
cd ~/myprojects/helloworld
C:Usersmyusername> cd myprojectshelloworld
C:Usersmyusernamemyprojectshelloworld>
C:Usersmyusernamemyprojectshelloworld> javac -d . HelloWorldMain.java
Notice the -d . before the filename. The dot denotes the current directory. The –d option (destination directory) lets the Java compiler know where to put compiled class files based on their package namespace. In this scenario, the HelloWorldMain package statement (namespace) is helloworldmain, which will create a subdirectory under the current directory assuming we are in the myprojects/helloworld directory.
When finished compiling, your directory structure should resemble the following:
|myprojects
|helloworld
|HelloWorldMain.java
|helloworldmain
|HelloWorldMain.class
C:Usersmyusernamemyprojectshelloworld> java helloworldmain.HelloWorldMain
Shown in Figure 1-24 is the output of a simple JavaFX Hello World application launched from the command-line prompt.
Figure 1-24. JavaFX Hello World launched from the command-line prompt
Walking Through the 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 life cycle 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 Hello World application, having a main() method and an overridden start() method.
Listing 1-2. A skeleton version of the file HelloWorldMain.java
public class HelloWorldMain extends Application {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Main thread
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
// JavaFX application thread
// JavaFX code here...
}
}
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. To access any arguments passed into the launch() method you can invoke the getParameters() method of the Application class. Please see the Javadoc documentation for details on various ways to access named and raw arguments. 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 primaryStage) {...}
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 with running on Java Swing’s event dispatch thread. 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.
You’ll notice that some objects are oddly named, such as Stage and Scene. The designers of the API have modeled things on 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 that actors perform in. And, of course, all scenes are performed on a stage. 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 our example, in the start() method we 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 how to set the title and create the scene:
primaryStage.setTitle("Hello World");
Group root = new Group();
Scene scene = new Scene(root, 300, 250);
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. We’ll learn more about the Group class later when we 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>) that responds when the user presses the button. The handler code will output the word “Hello World” on the console.
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 our root Group via the getChildren().add() method, we set the primaryStage’s scene and call the show() method on the Stage object to display a JavaFX application window. By default the window will allow a user to minimize, maximize, and close (exit) the application. Following is the code to set the scene and display (show) the JavaFX application window (Stage):
primaryStage.setScene(scene);
primaryStage.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 JavaFX team has created a JavaFX Packager tool to assist developers to build, package, and deploy their applications. To learn more about how to use JavaFX Packager tool, please see Oracle’s “Deploying JavaFX Applications” at http://docs.oracle.com/javafx/2/deployment/jfxpub-deployment.htm.
To give you a taste of the JavaFX Packager tool’s capabilities, I will show you how to package the HelloWorldMain classes into a single executable jar file that a user can double-click or launch from a command prompt (terminal).
cd myprojects/helloworld
javac -d . HelloWorldMain.java
javafxpackager -createjar -appclass helloworldmain.HelloWorldMain -srcdir . -outdir out
-outfile helloworld.jar -v
Table 1-1 describes the common options and switches that are used in building a JavaFX jar executable application.
Table 1-1. Common javafxpackager Options to Build an Executable jar
Option/Switch |
Example |
Description |
---|---|---|
-createjar |
-- |
Creates a JavaFX JAR executable application. |
-appclass |
helloworldmain.HelloWorldMain |
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 javafxpackager. |
To run the jar executable on the command line, you simply type the following and press Enter:
javaw -jar out/helloworld.jar
There are many ways to package and deploy JavaFX applications. To learn more, please see Oracle’s “Deploying JavaFX Applications” at the following URL:
http://docs.oracle.com/javafx/2/deployment/jfxpub-deployment.htm
Also see the following, related articles:
Summary
So far you have managed to download and install both Java 8 JDK and NetBeans IDE. After successfully installing prerequisite software, you created a JavaFX Hello World GUI application through the NetBeans IDE and used a text editor to compile and run the binary class via a command-line prompt (terminal window). After learning two methods of compiling and running a JavaFX application, you did a quick code walkthrough of the source file HelloWorldMain.java. You also learned to package a JavaFX application as a standalone jar executable. Next, in Chapter 2 you will learn the fundamentals of JavaFX 8 such as drawing and coloring shapes as well as drawing text and changing text fonts.