Chapter     1

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!

Installing Required Software

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:

  • Windows OS (XP, Vista, 7, 8) 32- and 64-bit
  • Mac OS X (64-bit)
  • Linux (32- and- 64-bit)
  • Linux ARMv6/7 VFP, HardFP ABI (32-bit)
  • Solaris (32- and 64-bit)

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:

  1. Install the Java 8 JDK. Launch the binary executable. The screen in Figure 1-1 will appear once you’ve launched the JavaFX SDK setup executable. That’s a security warning you’ll commonly receive on the Windows platform to inform you about installing software. Typically other operating systems will pop up a similar warning dialog box to alert you of risks of installing or running binary files. Click the Run button to proceed. Typically you will need administrator rights on the machine to install software. On Windows you can right-click the executable and run as Administrator.

    9781430264606_Fig01-01.jpg

    Figure 1-1. The Windows Security Warning dialog window

  2. Begin the setup of the Java 8 JDK. The screen in Figure 1-2 will appear, to begin the installation process. Click the Next button to begin installation.

    9781430264606_Fig01-02.jpg

    Figure 1-2. Java SE Development Kit 8 setup

  3. Select optional features such as additional development tools, source code, and the Java runtime environment. Accept the default selections and click the Next button to install software components. Figure 1-3 shows the screen for optional features to install.

    9781430264606_Fig01-03.jpg

    Figure 1-3. Java SE Development Kit 8 optional features

  4. The installation process will display a progress bar, as shown in Figure 1-4.

    9781430264606_Fig01-04.jpg

    Figure 1-4. Java SE Development Kit 8 installation in progress

  5. Change the installation directory of the Java runtime. Accept the defaults and click Next to proceed. Figure 1-5 shows the Destination Folder dialog, where you can change the Java runtime installation directory.

    9781430264606_Fig01-05.jpg

    Figure 1-5. The Java 8 runtime destination directory

  6. Complete the installation of the Java 8 SE Development Kit. Click the Close button to exit. Shown in Figure 1-6 is the prompt that you have successfully installed the Java 8 SE Development Kit.

9781430264606_Fig01-06.jpg

Figure 1-6. Java 8 runtime destination directory

Setting Environment Variables

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.

9781430264606_Fig01-07.jpg

Figure 1-7. Windows Environment Variables

  • To set your JAVA_HOME for the Mac OS X platform, you will need to launch a terminal window to edit your home directory’s .bash_profile file (for example, named ~/.bash_profile) by adding the export commands shown earlier.
  • 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.
  • 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.

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.

Installing the NetBeans IDE

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:

  1. Download the NetBeans IDE from the following location:
    https://netbeans.org/downloads/index.html
  2. Install NetBeans 8 or later. Launch the binary executable. The screen in Figure 1-8 will appear once you’ve launched the NetBeans installation executable. On the Windows platform you will receive a security warning to inform the user about installing software.

    9781430264606_Fig01-08.jpg

    Figure 1-8. Windows security warning

  3. Click on the Run button to proceed. Figure 1-8 shows a Windows security warning prompt that appears before launching binary files.
  4. Begin the NetBeans IDE installation process. Click the Next button. Figure 1-9 prompts the user to begin the installation process.

    9781430264606_Fig01-09.jpg

    Figure 1-9. NetBeans IDE installer

  5. 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. Figure 1-10 shows the NetBeans License Agreement.

    9781430264606_Fig01-10.jpg

    Figure 1-10. NetBeans license agreement

  6. Read and accept the JUnit license agreement. After reading and agreeing to the terms, click “I accept the terms in the license agreement. Install JUnit” and then click the Next button to proceed.
  7. Shown in Figure 1-11 is the JUnit License Agreement. JUnit is a Java unit testing library.

    9781430264606_Fig01-11.jpg

    Figure 1-11. JUnit license agreement

  8. Choose the destination directory to install NetBeans and select the Java 8 SE Development Kit previously installed. As usual, keep the defaults for the destination to install the NetBeans IDE. However, you will need to select the correct JDK.
  9. Figure 1-12 shows a drop-down where you can specify the JDK for the NetBeans IDE. You will select the Java 8 JDK.

    9781430264606_Fig01-12.jpg

    Figure 1-12. NetBeans IDE installation

  10. The next stage is choosing the installation directory folders for NetBeans and the JDK; accept the defaults and click Next to proceed with installation. Figure 1-13 depicts the installation destination directories for NetBeans IDE and JDK.

    9781430264606_Fig01-13.jpg

    Figure 1-13. NetBeans IDE installation selecting JDK 8

  11. 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-14, the installer defaults to having Check for Updates selected.

    9781430264606_Fig01-14.jpg

    Figure 1-14. Check for Updates

    Shown in Figure 1-15 is the installation progress bar.

    9781430264606_Fig01-15.jpg

    Figure 1-15. Installation progress

  12. To complete the setup, in Figure 1-16 you will be prompted for an optional check box to contribute to the NetBeans team 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.

    9781430264606_Fig01-16.jpg

    Figure 1-16. Setup complete

  13. Launch the NetBeans IDE. You should see the opening page shown in Figure 1-17.

9781430264606_Fig01-17.jpg

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.

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 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.

  1. Launch NetBeans IDE.
  2. On the File menu, select 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-18 shows the New JavaFX Application dialog wizard to create a simple HelloWorld application.

    9781430264606_Fig01-18.jpg

    Figure 1-18. New JavaFX Application wizard

  7. On this screen click the Manage Platforms button. Make sure the field Platform Name contains JDK 1.8. Figure 1-19 depicts the JDK Home, Classes, Sources, and Javadoc directory locations. Once you have verified them, click the Close button.

    9781430264606_Fig01-19.jpg

    Figure 1-19. The Java Platform Manager window containing JDK 1.8 as a managed platform

  8. In Figure 1-18 make sure the Create Application Class option is selected. Then click Finish. 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-20 shows a newly created HelloWorld project.

    9781430264606_Fig01-20.jpg

    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 image Set Main Project image 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.

  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 8, as shown in Figure 1-21. Click Sources under Categories.

    9781430264606_Fig01-21.jpg

    Figure 1-21. Project Properties

  10. To run and test your JavaFX Hello World application, ensure the project folder is selected (left Projects tab), then click on the green Run button to execute the HelloWorld project. Notice in Figure 1-22 showing the Set Main Project menu selection set to None. This will ensure the HelloWorld or any other project can run without having to be so explicit. This frees the developer to switch projects quickly.

    9781430264606_Fig01-22.jpg

    Figure 1-22. Setting the HelloWorld project as the Main Project

  11. Select the Run menu and Run Main Project or hit the F6 key. You can also click the green arrow icon on the tool bar. After you hit the Run option, the output should look like Figure 1-23.

9781430264606_Fig01-23.jpg

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.

Using the Command-Line Prompt

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.

  1. Copy and paste the code from Listing 1-1 into a text editor, and save the file as HelloWorldMain.java.
  2. After saving the file named HelloWorldMain.java, on the command-line prompt you will navigate to the directory location of the file. The examples to follow assume you have saved the file to a directory named myprojects/helloworld. Change directory as follows on Mac OS X, Linux, and Unix-based operating systems:
    cd ~/myprojects/helloworld
  3. Change directory on Windows operating systems using the following command:
    C:Usersmyusername> cd myprojectshelloworld
    C:Usersmyusernamemyprojectshelloworld>
  4. Compile the source code file HelloWorldMain.java using the Java compiler javac with the -d switch with the current path. Type the following command:
    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
  5. Run and test your JavaFX Hello World application. Assuming you are located in the same directory as the HelloWorldMain.java file, type the following command to run your JavaFX Hello World application from the command-line prompt:
    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.

9781430264606_Fig01-24.jpg

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.

JavaFX Scene Graph

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);

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. 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.

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

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