Chapter 2. Introduction to JavaFX

As described by Sun, JavaFX is an expressive and rich client platform for creating and delivering immersive Internet experiences across different screens. The main intention of this technology is to write Rich Internet Applications (RIAs) that run seamlessly across screens (desktop, mobile, or IP TV), providing a uniform user experience. JavaFX applications are written using a statically typed, declarative language called JavaFX Script that makes it easy to program in a visual context, enabling developers to create highly expressive and intuitive GUIs quickly and easily.

JavaFX is fully integrated with the Java Runtime Environment (JRE) and takes full advantage of the performance and ubiquity of the Java platform. JavaFX applications will run on any desktop and browser that runs the JRE and easily integrate with Java Platform, Mobile Edition (Java ME), opening the door to billions of mobile phones and other connected devices! JavaFX also leverages the other benefits of the Java platform, such as object-orientation, inheritance, polymorphism, a well-established security model, well-defined exception handling, memory management through garbage collection, and the mature Java Virtual Machine (JVM).

Why JavaFX

Developers are seeking the most efficient way of creating expressive content in applications that appear on desktops, on the Internet, and on mobile devices. They need to build high-fidelity GUIs that operate seamlessly on multiple web browsers, operating systems, and devices, without having to port or rewrite their applications for each screen. To meet this goal, developers need to work efficiently with team members such as graphic designers and media authors to exchange audio, video, and other rich media assets. The JavaFX platform contains an essential set of tools and technologies that enable developers and designers to collaborate, create, and deploy applications with expressive content.

Advantages of JavaFX

JavaFX is a full-fledged development platform for RIAs and has many advantages over other equivalent technologies in the market. Out of all, there are some key factors that differentiate JavaFX significantly.

  • RIAs for all screens: JavaFX provides a unified development and deployment model for building expressive RIAs across desktop, browser, mobile, and TV.

  • Rich client platform: JavaFX makes it easy and intuitive to integrate graphics, video, audio, animation, and rich text.

  • Ease of use: JavaFX Script is an easy-to-learn, easy-to-implement language that is statically typed, offering a declarative syntax that makes it easy to program in a visual context without worrying about the internals.

  • Powerful runtime: JavaFX leverages the extreme ubiquity, power, performance and security of the JRE.

  • Time-to-market: JavaFX offers a dramatically shortened production cycle for designers and developers through its designer–developer workflow. JavaFX allows you to incorporate multimedia assets from popular third-party design tools such as Adobe Illustrator and Photoshop using the JavaFX Production Suite.

  • Ready-made mass market: JavaFX allows you to distribute your RIAs widely, more quickly and easily across billions of Java-powered devices.

  • Preserve your investment: You can reuse your existing Java libraries in JavaFX and thus preserve the investment you've already made in Java.

  • Cross-browser functionality: JavaFX provides a uniform user experience across all browsers on multiple platforms.

  • Enterprise Integrations: With JavaFX you are ready to integrate a rich UI with a complex enterprise back-end.

  • Proven Security Model: You'll get broader system access with the proven Java security model.

History of JavaFX

JavaFX was originally known as F3 (Form Follows Function) and was a pet project of Christopher Oliver, a software engineer at Sun Microsystems who came onboard through Sun's acquisition of SeeBeyond. At the JavaOne 2007 conference, Sun officially launched F3 as the JavaFX platform, and it had an interpreter-based language by then. In July 2008, Sun launched its first preview version of JavaFX with its own compiler. JavaFX 1.0 was released in December 2008 with many more enhancements and optimizations to the platform.

JavaFX 1.1 was released in February 2009. Its primary focus was the mobile platform, and JavaFX was made fully functional on mobile devices, as demonstrated at the Mobile World Conference in February 2009.

Sun continued adding more features, optimizations, and performance improvements, and it released JavaFX 1.2 at the JavaOne 2009 conference. At press time, Sun is currently working on JavaFX 1.3, tentatively targeted to be released in early 2010.

The JavaFX Platform

The JavaFX 1.2.1 platform release includes various components, as illustrated in Figure 2-1. Let us see each one of them in detail.

The JavaFX platform: an overview

Figure 2.1. The JavaFX platform: an overview

The Developer Bundle

The developer bundle consists of the following elements:

  • NetBeans IDE 6.7.1 for JavaFX 1.2.1: This provides a sophisticated integrated development environment for building, previewing, and debugging JavaFX applications. The editor features a drag-and-drop palette so you can quickly add JavaFX objects with transformations, effects, and animation. This IDE also comes with its own set of building block examples and the JavaFX Mobile Emulator, a mobile phone simulator.

  • JavaFX Plug-in for NetBeans IDE: If you are already using the NetBeans IDE, you can add the JavaFX plug-in to include support for developing JavaFX applications.

  • JavaFX Plug-in for Eclipse IDE: Sun also offers a JavaFX plug-in for the Eclipse IDE, which works with Eclipse IDE 3.4 or newer.

The Designer Bundle

The designer bundle consists of JavaFX Production Suite, a single download that contains the following tools to enable designers to exchange visual assets with developers:

Plug-ins for Adobe Illustrator and Adobe Photoshop: Plug-ins are available for popular designer tools such as Adobe Photoshop and Adobe Illustrator that allow designers to export the visual assets created by these tools to JavaFX applications. Developers can start building their applications based on mockups that the designer creates. As the visual design evolves, it is easy for the developer to incorporate changes in the artwork for the final version of their application. When a designer saves a graphic to the JavaFX format, they can compare how it will look in desktop and mobile applications, and they can view metrics that enable them to minimize resource demands on mobile devices.

JavaFX Media Factory: This contains two separate tools:

  • SVG Converter: Converts SVG Content into JavaFX Format.

  • JavaFX Graphics Viewer: Allows you to view graphic assets that were converted to the JavaFX format. It allows you to preview each graphic as it will appear in either desktop or mobile applications.

Standalone

If you prefer using other tools, or developing directly via the command line, you can download the stand-alone JavaFX 1.2.1 SDK. The SDK includes the following components (also included when you download NetBeans IDE for JavaFX):

  • JavaFX Desktop Runtime

  • JavaFX Mobile Emulator (for Windows)

  • JavaFX APIs

  • JavaFX Compiler

  • JavaFX API documentation

  • Examples

JavaFX Platform Integration: The Bigger Picture

Figure 2-2 illustrates the bigger picture of how the JavaFX platform integrates different platform elements, the runtime, tools, and frameworks to deliver applications, content, and services to consumers using multiple devices.

The JavaFX Platform: the bigger picture

Figure 2.2. The JavaFX Platform: the bigger picture

Here is a brief introduction to each of the elements illustrated in Figure 2-2:

  • JavaFX Runtime: Contains cross-platform and platform-specific runtime environments and supporting libraries.

  • Common Elements: Contains APIs and other runtimes that work consistently across platforms.

  • Desktop Elements: Contains API extensions that are specific to the desktop platform.

  • Mobile Elements: Contains API extensions that are specific to the mobile platform.

  • TV Elements: Contains API extensions that are specific to the TV platform.

  • Application Framework: Forms the building block for application development.

  • Designer Tool: Allows visual designers and graphics experts to create graphic assets using popular content authoring tools such as Adobe Photoshop and Adobe Illustrator and bring those assets into the JavaFX application using the respective JavaFX plug-ins provided by Sun Microsystems. This shortens the production cycle of RIAs drastically. Sun is also working on its own content authoring tool, a preview of which was demonstrated at JavaOne 2009.

  • Developer Tool: Helps developers create JavaFX applications, services, and content.

JavaFX Mobile: An Introduction

With JavaFX Mobile, Sun is bringing expressiveness to the most powerful and pervasive mobile platform. On mobile devices, JavaFX runs directly on Java ME to take advantage of the platform's ubiquity, security, and highly capable feature-set. With JavaFX Mobile, developers and designers benefit from using the same JavaFX tools, such as the JavaFX SDK and the JavaFX Production Suite, that they have been using to create content for the desktop and browser. This makes it much easier to start creating mobile content, and it opens up the mobile device to a much wider pool of developers and designers.

Consumers today expect richer experiences on their mobile devices and also want their content to work well in bandwidth-constrained network environments and in offline modes. However, creating content for mobile devices typically requires highly specialized programming skills that many content and service providers may not have in-house. Moreover, as companies look to deliver their content and services to consumers across all of their devices (Mobile, Desktop, TV, and so on), they want to do so with a consistent and device appropriate user experience. Developers want an easier way to create rich and expressive content for mobile devices and want to be able to collaborate with team members such as graphics designers and media authors in an efficient manner that allows simple exchange of audio, video and other rich media assets. Device manufacturers want to enable richer experiences while leveraging their existing technology investments. Thus everyone from device manufacturers to service providers to developers to end consumers benefits from the combination of Java and JavaFX Mobile.

Advantages of JavaFX Mobile

Here are the advantages of using the JavaFX Mobile platform to develop and deliver expressive content:

  • You can get your content in front of more users than with any other platform by cutting across multiple OEMs and platforms.

  • JavaFX makes it easy to design dynamic interfaces that integrate audio, video, text, graphics, and animation!

  • Java is backed by nearly all operators and OEMs, making it the strongest platform in the industry.

  • JavaFX Mobile lets operators and OEMs build on their existing investment in Java to lower their implementation costs.

  • JavaFX Mobile allows developers to build expressive interfaces while reusing existing Java code.

  • JavaFX Mobile provides the broadest access to device-level capabilities of any cross-device platform.

  • JavaFX Mobile protects the user through a proven security model that enables safe access to data and device capabilities

  • JavaFX Mobile provides strong developer tools along with a better developer–designer workflow that leverages existing, popular tools.

  • Developers can easily target their content across desktops and mobile devices with a single, unified SDK and a common API.

  • JavaFX Mobile provides a full mobile emulator to prototype and optimize content directly on your desktop. As of JavaFX 1.2.1, the supported mobile devices are HTC Diamond and LG Incite.

Deployment and Distribution

At one time we used to think of computers as the center of the Internet. But of late, the reach of the Internet has become entirely global and has gone well beyond just computers as a delivery mechanism, extending to a world of devices such as mobile phones, Internet billboards, set-top boxes, car dashboards, and more. All these devices touch consumers on a daily basis in every aspect of their lives, and consumers obviously want to stay connected wherever they are with whatever devices they have. Java as a technology caters to the needs of these consumers, and Java is presently deployed on billions of devices globally and has a developer base of over 6 million. JavaFX leverages the ubiquity of Java and hence allows JavaFX developers to reach a wider audience over more devices than any other technology.

JavaFX applications can be deployed and distributed in the following ways:

  • Java Plug-in: A tool used for deploying Java applets that run inside a web browser.

  • Java Web Start: A tool used for deploying standalone Java applications on the desktop, using Java Network Launching Protocol (JNLP).

  • The Java Store: JavaFX applications can be submitted for distribution through the Java Store. End users can go to the Java Store and "drag to install" or perform a traditional installation directly to their desktops.

The JavaFX SDK contains a JavaFX Packager utility, which creates an application in a format that is specific for a target profile, either desktop or mobile. The NetBeans IDE incorporates this utility and is available to users when they choose an execution model.

Getting Started

This section will get you started using the NetBeans IDE to write a small "Hello World" program in JavaFX, compile it, and execute it on multiple platforms.

What to Download

First make sure that you meet the system and software requirements listed at http://java.sun.com/javafx/1/reference/system–requirements–1–2.html. Check that you have the required hardware and available free disk space, and the correct version of the Java Software Development Kit (JDK) or Java Runtime Environment (JRE) before proceeding with any of the following installation instructions.

Application developers should download the following:

  • If you are new to the NetBeans IDE: Download and install NetBeans IDE for JavaFX 1.2.1. This version is available for Windows and Mac OS X platforms. A beta release is available for Ubuntu and OpenSolaris platforms. The NetBeans IDE for JavaFX 1.2.1 is a full-featured development environment that is packaged with the JavaFX Software Development Kit (SDK) and with best-practice examples that can help you build your software development project. The installation includes the JavaFX Mobile Emulator, which is currently available only on the Windows platform. (Future releases of JavaFX may also have an emulator available on the Mac platform.)

  • If you already have NetBeans IDE: Update your IDE with JavaFX 1.2.1 Plug-in for NetBeans. This version is available for Windows and Mac OS X platforms. A beta release is provided for the Ubuntu Linux and OpenSolaris platforms. The plug-ins provide the features that support the development of JavaFX applications in the NetBeans IDE. They also include the JavaFX SDK and best-practice examples. The installation includes the JavaFX Mobile Emulator, which is currently available on the Microsoft Windows platform only.

Now let's learn how to start a new project in NetBeans to create a "Hello World" program.

Writing Your First JavaFX Application

In this section, you will learn how to write a simple "Hello World" JavaFX application using NetBeans.

  • Make sure you have installed and set up the NetBeans IDE along with the Java Development Kit.

  • Start the NetBeans IDE.

  • Click the File menu and choose the New Project menu item, as shown in Figure 2-3.

    The NetBeans main screen with the New Projects option

    Figure 2.3. The NetBeans main screen with the New Projects option

  • Select JavaFX from Categories. Click the Next button as shown in Figure 2-4.

    The NetBeans: New Project screen

    Figure 2.4. The NetBeans: New Project screen

  • Enter the Name and Location of the JavaFX project as shown in Figure 2-5.

    The NetBeans New Project screen with project details entered

    Figure 2.5. The NetBeans New Project screen with project details entered

  • Click the Finish button.

  • Now you'll see that a new JavaFX Project has been created; the screen looks as shown in Figure 2-6. You will see a Main.fx file; this is a default file that NetBeans has created. Modify the string "Application content" to read "Hello World from JavaFX." and change the content of the title to "Hello JavaFX" as shown in Figure 2-6.

The Main.fx file in NetBeans

Figure 2.6. The Main.fx file in NetBeans

Notice that JavaFX Script code is included within the Main.fx file by default. This code, listed below, includes several import statements and object literals. These literals represent key concepts within the JavaFX application, and are described in detail after the code snippet.

/*
 * Main.fx
 *
 */

package helloworld;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;

/**
 * @author Lawrence & Praveen
 */
Stage {
title: "Hello JavaFX"
    width: 250
    height: 80
    scene: Scene {
        content: Text {
            font : Font {
                size : 16
            }
            x: 10, y: 30
            content: "Hello World from JavaFX"
        }
    }
}

The following object literals are created by default:

  • Stage: The top-level container required to display any visible JavaFX objects. This can be considered as an equivalent of a java.awt.Frame or java.awt.Window in Java. Default instance variables such as title, width, and height are attributes of the stage. Scene attribute defines the client area within the stage.

  • Scene: Similar to a drawing surface for the graphical content of your application. A scene instance variable has a content attribute that holds the actual graphical elements to be displayed.

  • Text: Displays textual information in the scene.

  • Font: Defines the font used to display the text in the scene.

The concepts of stage and scene can easily be related back to real-world scenarios in which a stage is normally a platform on which a scene would be presented, and a scene is normally created by various actors. So in this case, a scene is composed of actors such as text, and the scene is shown from within a stage. The JavaFX developers deliberately defined the APIs to be in sync with the real-world scenario to keep the platform simple, easy-to-understand, and intuitive to even nonprogrammers.

Running Your Application Using NetBeans

There are thee modes in which you can deploy this application using NetBeans: standalone, browser/Java Web Start, and Mobile Emulator. Let's see each one of them in detail.

Standalone Mode

The default mode set in NetBeans in the standalone mode, and running the project as-is without modifying any configuration parameters will run the application in standalone mode.

There are two ways to do this: First, you can just click the

Standalone Mode

The output of our application run in standalone mode would look like Figure 2-7.

The output of Main.fx

Figure 2.7. The output of Main.fx

Browser/Java Web Start Mode

To run our "Hello World" application on the browser, right-click on the project and go to Properties. As shown in Figure 2-8, choose Run option from the list on the left and click the Run In Browser radio button for Application Execution Model.

NetBeans: Running in Browser mode

Figure 2.8. NetBeans: Running in Browser mode

To run it as a Java Web Start application, choose Web Start Execution as the Application Execution Model, as shown in Figure 2-9.

NetBeans: Running in Web Start mode

Figure 2.9. NetBeans: Running in Web Start mode

After choosing the application execution model, choose Application from the list on the left side and set the appropriate width and height for the applet, as shown in Figure 2-10.

NetBeans: Setting application properties

Figure 2.10. NetBeans: Setting application properties

The project is now all set for executing on the browser, so just right-click and select Run Project or press F6 if this is the Main project. NetBeans will automatically open up the default browser on your platform and run the application.

Mobile Emulator

To run the "Hello World" program on Mobile Emulator, choose Run in Mobile Emulator as the Application Execution Model, as shown in Figure 2-11.

NetBeans: Running in Mobile Emulator mode

Figure 2.11. NetBeans: Running in Mobile Emulator mode

After choosing the execution model, just right-click and select Run Project or press F6 if this is the Main project. You will see the output shown in Figure 2-12.

Output of Main.fx on Mobile Emulator (Windows)

Figure 2.12. Output of Main.fx on Mobile Emulator (Windows)

Note

fx is the file extension for a JavaFX program. JavaFX also has a compiler and an interpreter. javafxc is the JavaFX compiler, which converts a JavaFX program to .class files (byte code); javafx is the JavaFX interpreter, which takes the .class file and executes it.

At this point, you may compare our JavaFX Script program with a Java or C/C++ application and wonder where the entry point is. In JavaFX, there is no need to bother about the entry point; it is taken care by the JavaFX runtime engine, because JavaFX is a "declarative programming language" (one that determines its path of execution at runtime). However, in certain cases, you will need a run() method to be included in your application; you'll learn more about that in later chapters.

Running the Application from the Command Line

This section will outline how to build and run the application from the command line for people who do not use IDEs. Let's assume you have typed the code of Main.fx in a text editor and saved it in some location on the file system, such as c:helloworldMain.fx.

First take care of the following prerequisites:

  • JAVA_HOME must be set to the recommended JDK, namely c:jdk1.6.0_14. Don't include the bin folder.

    JAVAFX_HOME must be set to the JavaFX SDK, which you can download separately from www.javafx.com); for example, c:javafx-sdk1.2. Don't include the bin folder.

    PATH must be set to %JAVAFX_HOME%in. This is more of a convenience, as it allows you to use JavaFX and JavaFXC executables directly without specifying the full path.

Compiling the Application for Standalone Execution

To run in standalone mode from the command line, the application must be first compiled for execution. Take the following steps to compile the JavaFX program:

  1. Make sure you create a folder to store the class files, called, say, classes, at the same level as the helloworld folder; for example, c:classes if you have the source code under c:helloworld.

  2. Give the following command:

    javafxc -d classes helloworld/Main.fx

    where -d specifies where to store the class files. This will compile Main.fx and store all the class files under c:classes.

  3. To run the application, give the following command:

    javafx -classpath classes helloworld.Main

This will display the output shown earlier, in Figure 2.7.

Compiling the Application for Browser/Java Web Start Execution with JavaFX Packager

In order to build the application to run on a browser or in Java Web Start, we need to use the JavaFX Packager. Let's examine this tool in detail.

JavaFX Packager is a command-line utility that comes with the JavaFX SDK and helps developers build applications seamlessly for whatever profile they want to deploy on. It is a single utility that you use to build your application for standalone, browser, Web Start, or mobile. NetBeans IDE internally uses this utility to build your application.

JavaFXPackager requires the following mandatory input parameters:

  • -src: The directory where source files are available

  • -profile: The target profile (such as MOBILE or DESKTOP)

  • -appClass: The main class for your application, the entry point

JavaFXPackager also allows the following optional parameters:

  • -appWidth: Required for Web Start/browser mode, specifies the application width. The default value is 200.

  • -appHeight: Required for Web Start/browser mode, specifies the application height. The default value is 200.

  • -sign: Specifies whether the application must be signed; required for browser/Web Start mode. The default value is unsigned. An application must be signed if it accesses any local resources or remote resources from a server that is different from the one where the application will be hosted.

  • -draggable: Specifies whether the applet must be draggable from browser on to the desktop. By default, applets are not draggable.

  • -res: Any resources used by the application, such as images, media, and so on.

Building and Running the Application Using JavaFX Packager for the DESKTOP Profile

To build the application for running on browser, give the following command (note that a dot can be used to represent the current directory):

<JAVAFX_HOME>/bin/javafxpackager -src c:helloworld -appClass helloworld.Main -profile DESKTOP -appWidth 250  -appHeight 80  -draggable

This will create a folder dist in the current directory, which will contain the following:

  • Main.jar: This contains the classes and resources.

  • Main.jnlp: This is a jnlp file that can be launched using Java Web Start.

  • Main_browser.jnlp: This helper jnlp file facilitates running the application on the browser.

  • Main.html: This is an HTML file embedding the JavaFX applet.

Now to run the application on a browser, just load the HTML file in the browser and the applet will be loaded.

To run it on Java Web Start, you can open the Main.jnlp file from the browser. You can also double-click it if the JNLP mime type is configured properly on your native side and on the browser. If configured properly, Java Web Start will show the download progress dialog.

Alternatively, you can run the application from the command line, as follows:

<JAVA_HOME>/bin/javaws Main.jnlp

To run it as a plain standalone application, you can use the following command:

<JAVAFX_HOME>/bin/javafx -classpath Main.jar helloworld.Main

Building and Running the Application Using JavaFXPackager for the MOBILE Profile

To build the application to run on Mobile Emulator, give the following command:

<JAVAFX_HOME>/bin/javafxpackager -src "c:helloword" -appClass helloworld.Main -profile MOBILE

This creates a dist folder with two files in the current directory:

  • Main.jar: A jar file containing the classes and resources.

  • Main.jad: The descriptor file that the emulator platform can decode.

To launch the application on Mobile Emulator, give the following command from within the dist folder:

<JAVAFX_HOME>/emulator/bin/emulator -Xdescriptor:Main.jad

This will open up the Emulator and load the application as well. There are additional parameters for Emulator, such as the device type, memory, and so on, but those are optional.

Note

Executing the application on the browser or Java Web Start requires an Internet connection the first time, since the JavaFX runtime will be downloaded from the web dynamically when the application is launched. However, subsequent executions will use the locally cached runtime unless the user has explicitly cleared the cache or the contents of the cache have gone past the time-out period.

Comments

When writing code in any language, it is important to remember to include written comments about what each line or group of statements is doing. To keep the JavaFX interpreter from trying to execute this text, you must hide it between comment characters. Table 2-1 shows the two types of comments available in JavaFX.

Table 2.1. Comment Markers in JavaFX

Comment Type

Description

// comment

All characters after the // to the end of the line are ignored.

/* comment */

All characters between /* and */ are ignored. These comments can extend onto multiple lines.

Note

Comment syntax in JavaFX is the same as in Java. If a line of code does something important, it is useful to call attention to it with a short comment. It is always considered "good programming" to provide comments for all your code to help future programmers (including yourself) understand what's happening.

The type of comment you use and the purpose you use it for are entirely up to you, the programmer. Two styles of commenting programs are the Sun Microsystems and Microsoft styles. Most of the Sun documentation uses the following style for multiple lines, because it is useful with the automatic document generator that comes with the Java Development Kit:

JavaDoc Style
 /**
     *  this is a multi-lined comment
     *  for the following class
     *
     */

The JavaDoc Style tag tells the document generator to use the comments as text in the resulting HTML file that is created automatically from source code. It is nice to get into the habit of using it.

Summary

In this chapter, we have introduced what JavaFX technology is all about, including its advantages, platform components, and the bigger picture of where this technology fits in. We have also taken you through a tour of how to use the technology to develop a simple "Hello World" application through the NetBeans IDE as well as in standalone mode, and you learned how to deploy the application for the desktop, browser, Java Web Start and emulator. In the next chapter, we will dive into the JavaFX Script language to explore the data types it offers to programmers.

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

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