devxlogo

JavaFX Enters the RIA Race

JavaFX Enters the RIA Race

ich Internet Application or RIAs are all the rage in application development circles now. How do you make web applications behave like more traditional desktop applications? You remember desktop applications don’t you? Harken back to the days of drag-and-drop, slide bars, dynamic widget enabling, disabling, background coloring, etc.?all to make the user experience more pleasing without the “flash-bang,” slow-performing Web page refreshes. Those were some user interfaces!

AJAX is the technology most often used today to provide RIAs that present the closest thing to desktop applications offered over the Web. AJAX has been a part of a new Web revolution,heralded as Web 2.0. The unfortunate aspect of AJAX is its dependency on the platform. Namely, if you have ever written an AJAX application for mass distribution, much of the application code is littered with “if Microsoft IE do…if Mozilla or other browser do…” conditionals. Efforts by the W3C and others to standardize AJAX technologies are helping, but they may not be enough when you’re also considering needs to bring more dynamic applications to other platforms like mobile and consumer devices.

AJAX is based on relatively older software technology. JavaScript, DOM, XHTML, etc. have been around a while and are seeing rebirth in RIA needs. However, industry leaders are waking up to the RIA need and are looking to satisfy it with some new (and some might say better) technology. For example, Microsoft has stepped up with XAML (Extensible Application Markup Language) in the Windows Presentation Foundation of .NET 3.0, where it is used as a user interface markup language to define UI elements, data binding, event handling, etc. Their Silverlight product provides a subset of WPF functionality on mobile devices and other platforms.

JavaFX was heavily spotlighted at this year’s JavaOne conference and it’s clearly Sun and the Java community’s most current entry to the RIA competition. JavaFX is actually intended to be a family of products initially comprised of JavaFX Script and JavaFX Mobile. JavaFX Script (JavaFX for short) is a scripting language meant to provide rich user interfaces using syntax that resembles JavaScript and Scalar Vector Graphics (SVG). As its name implies, JavaFX Mobile is intended for use on mobile platforms.

This article introduces you to the new JavaFX Script language. I point you to some JavaFX syntax and API tutorials and take you through some of the interesting characteristics that might make JavaFX appealing. It is a technology still in its infancy, but if you are thinking RIA long term, it’s a technology worthy of inspection. Why? As the JavaFX FAQ states:

“JavaFX Script will enable developers to more quickly and easily develop RIAs and next-generation services that can be proliferated across virtually any device?from desktop browsers and mobile devices, to set-top boxes and Blu-ray Disc DVDs?securely and without local installation.”

Java is the dominant application platform on handsets. Marry that lead, the “write once, run anywhere” mantra, and the need for RIA, and you start to understand why Sun is pushing hard to establish JavaFX as a powerful development technology. Sun wants to keep and expand Java deployments and JavaFX is a means to that goal.

A recent (July 2007) podcast given by Jacob Lehrbaum, Sun’s JavaFX Mobile product line manager, suggest that Sun will be working with device vendors this fall in order to bring JavaFX Mobile-capable devices to market in 2008. Even development tools are still a few months off. In the podcast, he says “I think it’s a little bit early to start working with [JavaFX Mobile] as we are still defining the platform and building out some of those capabilities.” He recommends getting familiar with JavaFX Script via OpenJFX (more below) and NetBeans plugins as a means to get ready for this new mobile device capability.

Set Up JavaFX
All that is required to run JavaFX scripts on the desktop is a JRE. Both Eclipse and the NetBeans IDEs already offer plug-ins to start working with JavaFX; getting set up to learn it is pretty painless.

To configure NetBeans 5.5 for JavaFX, simply use the built in NetBeans Update Center (see Figure 1). Through the OpenJFX project and web site, Sun provides step-by-step instructions on how to use the Update Center and configure NetBeans 5.5 with the JavaFX plug-in.


Figure 1. The NetBeans Update Center: Here’s where to retrieve and configure the JavaFX plug-in for use in NetBeans.
 
Figure 2. The Eclipse Features Update: Use this mechanism to locate and install the JavaFX plug-in.

Specifically, these instructions have you install the OpenJFX implementation of JavaFX. OpenJFX is the Sun project for “sharing early versions of the JavaFX Script language and for collaborating on its development.” A plug-in is also available for those that have already graduated to the NetBeans 6 Preview.

Likewise, if you’re using Eclipse (version 3.2), you download and install a plug-in for Eclipse. Use the find and install option in Eclipse to download and configure the plug-in (see Figure 2).

If you’d rather not use an IDE, OpenJFX offers a download that includes the bare minimum; that is the JavaFX Script runtime, library source, and demo source code files.

Creating a JavaFX Project
Whether you’re using NetBeans or Eclipse, creating a JavaFX application is the same; simply create a plain Java application. In NetBeans, use the new project wizard to create the plain Java application.

Once the project has been created, right click on the newly created project in the Projects window and select the options to create a new Class.fx file (see Figure 3). The JavaFX code is written and stored in files with a .fx extension.


Figure 3. The NetBeans Class.fx File: Right click on the Java project and select the New option.
 
Figure 4. The Eclipse JavaFX File: Right click on the Java project and select the New?>Other… option.

In Eclipse, it is pretty much the same process. Use the wizard to create a new Java project

After the project is created, right click on the newly created project and select the options to create a JavaFX file (see Figure 4). In the ensuing New wizard, expand the JavaFX folder, select the JavaFX file, and hit the Next button. In the next window, enter the name of the JavaFX file.

JavaFX Script
Rather than use this article to detail the syntax and API of this new script language, I have given you a couple of example applications and point you to two OpenJFX pages that outline and document the syntax of JavaFX. Probably the best “informal documentation” on the basic syntax and structure of a JavaFX application is found here. After you have mastered the basic syntax, check out the online tutorial here. That page demonstrates the graphical user interface components in detail. Finally, if you are looking for the basic API documentation, check out the Javadoc-like set here. JavaFX is in its early stages. So documentation is still shy of what you would expect for other Java APIs or technologies, but these sources will let you start to discover JavaFX and evaluate its future.

As mentioned, attached to this article are a few JavaFX files/applications that are discussed and demonstrated below. These should also help you explore JavaFX.

The JavaFX Application
JavaFX Script is not a runtime environment; it is a scripting language that runs on top of a Java runtime. Is JavaFX Java or JavaScript? Well, perhaps you will see it as a little bit of both. JavaFX resembles JavaScript and other scripting languages in some of its syntax, but it also can use the standard Java syntax and make use of an extensive set of Java APIs. In fact, as you will see, the user interface components of JavaFX are tightly coupled to Swing and Java2D.

Where will JavaFX applications run? Sun’s hope is that JavaFX will run everywhere. Anywhere there is a Java runtime, JavaFX applications should be able to be run. In the smaller platform arena, JavaFX Mobile is a Java/Linux mobile and embedded operating system that Sun plans to distribute as a binary operating system to device manufacturers. Obviously, this platform is devised to host JavaFX apps. JavaFX Mobile is based on technology developed by SavaJe Technologies, which Sun purchased in April 2007.

Exploring the JavaFX Language?Declarative Syntax
Sun intends JavaFX to offer more rapid user interface development than pure Java. While this scripting language can be used for a whole host of application needs, it seems fitting to start to explore the JavaFX scripting language and its features from its point of strength. Namely, let’s look at using JavaFX to develop a user interface; in particular a login window. Again, JavaFX code is written in a file with a .fx extension. Compare the two files in (Listing 1 and Listing 2). Both create a login window (see Figure 5). The first uses JavaFX. The other uses traditional Java Swing. You might note some similarities in the class names used, but obviously the structure and makeup of JavaFX is quite different.

Figure 5. The Login Windows: On the left is the result of executing the Login.fx application. On the right is the result of running the more traditional Java Swing application Login.java.

This small example highlights the first major difference between JavaFX and plain Java. JavaFX uses declarative syntax like HTML to create the user interface. In a declarative syntax, you the developer specify what something is to look like rather than to write an algorithm on how to create it. The style of development that you have become familiar with in programming languages like Java is called imperative (also often called procedural) programming. Typically, declarative programming is easier to code and maintain, especially when building user interfaces that focus on the look.

It should be noted that you don’t have to use the declarative structure. You can create the exact same login window with JavaFX code using a procedural syntax (see Listing 3). This code uses procedural syntax, but results in an identical window display.

So, what is going on in the JavaFX code? The procedural form of the Login.fx file may help you to see, initially,what the declarative syntax defines. Just like in standard Java applications, the first line imports the JavaFX user interface components (more later). Then, an instance of a Frame is created, its properties are set, and it’s displayed or made visible to the user. In particular, the frame’s content is set with child elements of a GridBagPanel, composed of a set of cells each of which has a set of cells which each contain a label, entry field, or button widget. If the names or types of the “widget” elements sound familiar, that is because the JavaFX is closely aligned with Swing. The JavaFX Frame object wraps javax.swing.JFrame. The labels (SimpleLabel) are wrappers for javax.swing.JLabel. In fact, it is precisely because JavaFX is based on Swing that it offers a rich user interface capability (with a relatively low learning curve), but the declarative syntax helps remove some of the complexity.

Executing JavaFX
JavaFX applications on the desktop are executed by the FXShell. FXShell is a class provided in the OpenJFX download. To run JavaFX files in NetBeans, right click on the project in the Projects window and select Properties. In the Project Properties window that opens (see Figure 6), select Run in the Categories list and then enter net.java.javafx.FXShell as the Main class and your JavaFX filename (without .fx) in the Arguments list.


Figure 6. Using FXShell: In NetBeans, run a JavaFX file by having the JRE run FXShell and with your JavaFX file as an argument.
 
Figure 7. Running in Eclipse: Select the JavaFX file, right click on the file, and select Run As, and then Run….

To run JavaFX applications in Eclipse, right click on the JavaFX file in the Package Explorer view and select “Run As” and “Run…” from the menu (see Figure 7).

In the ensuing Run window, select JavaFX Application from the list on the left, and then push the New launch configuration icon at top of the window. This results in a “New_configuration” to be created under JavaFX Application. Optionally, change the name of the configuration to JavaFX. Notice that the main class to execute for this configuration is net.java.javafx.FXShell by default. Next, click on the Arguments tab and enter the name of the JavaFX file (without the .fx extension) in the Program Arguments field. When finished, hit Apply and then Run.

Figure 8. The Investment Calculator: Written entirely in JavaFX, the investment calculator allows the user to dynamically enter and change investment information and have the interface automatically calculate the investment return.

JavaFX Classes, Objects, and Automatic Data Binding
JavaFX is not restricted to user interfaces. You can also define classes. In this next example, you’ll build an investment calculator. The user interface allows a user to enter starting principal, annual contribution, rate of return, and amount of investing time data and calculate the investment return (see Figure 8). in The JavaFX code in Listing 4 provides an InvestmentTool class to capture the data entered by the user and calculate the return.

The keyword “class” with the code block ({} notation) obviously defines the InvestmentTool class. Properties are defined with the “attribute” keyword. Each attribute is defined with the following syntax:

attribute AttributeName : AttributeType Cardinality;

In the InvestmentTool example, the cardinality is not used but the cardinality can be used to define an array or optional property, as specified in Table 1.

Cardinality Indicator

 

?

Optional (i.e, the attribute is not required and may be null)

+

One or more

*

Zero or more

Table 1. Cardinality can be used to define an array or optional property.

Notice that the operations are declared in the class, but the implementation is specified outside the actual class declaration. Chris Oliver, a key member of the JavaFX team, has indicated part of the rationale for this is that “having method bodies in the class declaration clutters it with a mass of implementation details which is detrimental to getting an overview of the actual relationships and operations embodied by the class.”

Author’s Note: Chris Oliver’s weblog is good reading for those interested in more details about JavaFX and provides insight to some of the why’s/wherefores of F3, which is the original name of JavaFX.

In JavaFX, “methods” are defined as either functions or operations. A function is a method that may only contain a series of variable declarations and a return statement. So for example, a function to determine the length of a hypotenuse would look like the code below:

function hypotenuseLength (side1, side2){ var a = side1 * side1; var b = side2 * side2; var c = Math.sqrt(a+b); return c;}

An operation, on the other hand, can contain any number of statements (variable declarations, loops, conditionals, etc.). Additionally, similar JavaScript operations and functions can be first class objects and don’t have to be associated to a class?another reason for their being implemented outside of classes.

An instance of the InvestmentTool calculator is associated to the variable calculator in the statement var calculator = InvestmentTool{…} at the bottom of Listing 4. And, while JavaFX classes don’t have explicit constructors, the instance is created using this notation that allows the object instance to be created and attribute values to be initialized.

OK, so how are JavaFX classes and objects used? For example, how is this calculator instance used by a JavaFX user interface? Using a powerful JavaFX process known as automatic data binding, the attribute values of objects like calculator can be associated to properties of the user interface components. As the object changes, so does the components value and vice versa.

Listing 5 shows the JavaFX Frame user interface for the investment calculator. Notice how the “bind” keyword used in the value property of an input widget, like the annual contribution Spinner below. Binding allows the spinner’s value and the calculator’s annual contribution attribute to be tied to each other.

Spinner {	min: 0 max: 1000000 stepSize: 100 value: bind calculator.contributionAnnual font: Font{faceName: "Arial", size: 18}}

Triggers
Automatic binding keeps the user interface and objects synchronized. But how do actions like the return investment calculation get kicked off? Notice that in this user interface, there are no buttons for the user to push to initiate action. Another neat feature provided by JavaFX is triggers. Triggers are events that fire on data modifications. They behave like listener methods, but are simple to use and program. In this example, triggers were established for any update to any of the InvestmentTool attributes. In the trigger below, for example, anytime an InvestmentTool instance’s attribute numberOfYears is set to a new value, this “update” trigger fires resulting in a call to the getReturn() method.

trigger on InvestmentTool.numberOfYears = value { getReturn();}

However, a trigger can be set up for any type of object/data modification. Triggers can be set up for new instance creation or even insert, replacements or deletes to a multi-valued attribute (like an Array).

Static Typing
As you saw in the class definition of InvestmentTool (see Listing 4), attributes are typed. So are other variables in JavaFX. Unlike JavaScript, JavaFX is a statically typed language. Like JavaScript, however, if you don’t specify a type on a variable when it is declared, its type is determined based on its use. So, the following code implicitly types x as an Integer.

var x;x = 3;

However, because of its static typing, once set, a variable in JavaFX cannot be assigned a value of a different type. While the code below would be legal in JavaScript, in JavaFX, it results in an “IncompatiableTypes” compile error.

var x;x = 3;x = "hello";

Beyond classes/objects, JavaFX supports four primitive types: String, Boolean, Number, and Integer. These correspond to Java’s java.lang.String, java.lang.Boolean, java.lang.Number, and any of byte, short, int, long, or java.math.BigInteger for JavaFX’s Integer.

Java APIs
You may have noticed in the getReturn() or hypotenuseLength(a, b) methods described above, both made reference to Java’s java.lang.Math class and used one of its methods (see Listing 4). Just as in regular Java classes, the first lines of InvestmentCalculator.fx contain import statements.

import javafx.ui.*;import java.lang.Math;

Indeed, JavaFX programs can import and use Java classes and interfaces just as they are used in standard Java applications. Proponents of JavaFX are sure to highlight this feature as it allows JavaFX to reuse existing Java code and helps reduce the learning curve for those concerned about yet another scripting language.

JavaFX Still Young
The ability to quickly develop and more easily maintain rich GUIs that are based on the powerful and well-known Swing API gives JavaFX its appeal. While not Java, its Java base and ability to use Java when required or desired reduces the learning curve and allows for a great deal of immediate reuse. However, JavaFX is still very young and still gaining its sea legs. There are some issues you may want to consider before adopting JavaFX wholesale. It has even been suggested that JavaFX in its current state “doesn’t really give developers the ability to do much they couldn’t do already, its function is primarily to make existing Java technologies easier to use together.”

To date, there are no visual editors for JavaFX development. For a technology that aims to satisfy user interface and the RIA community needs, this will have to be rectified. It appears that this is a well-known need and one that is to be addressed shortly. As Chris Oliver has suggested in his weblog, “So far I haven’t spent time trying to develop serious visual tools to support [JavaFX] development, however once the language and API’s have stabilized that’s definitely something I want to do.”

Figure 9. Documentation: Using control-shift to get the code assist documentation for many classes in NetBeans shows just how much documentation work is still to be completed.

By the way, for those anticipating Sun is going to use JavaFX to replace Swing, Sun insists this is not the case. Directly from OpenJFX FAQ page, Sun says it “is not replacing Swing with JavaFX; instead, JavaFX Script makes Swing much easier to use.”

Developer documentation and IDE support is also thin. Even though plug-ins for NetBeans and Eclipse are available (as shown above), simple programming features such as syntax color highlighting and code formatting are missing. Even the code assist documentation suggests there is still a lot of work to be done. Open the documentation for many classes in the IDE and you notice how much “TODO” documentation placeholders exist in this early JavaFX release (see Figure 9).

Finally, the early versions of JavaFX don’t provide much insight on how this scripting language will integrate and tie into the larger application picture. For example, how will JavaFX assist with solid UI content and style separation? How will JavaFX applications at the client-side communicate effectively and asynchronously with the server-side? How do JavaFX applications get deployed or provisioned to the client, especially on mobile/consumer devices?

More Questions Than Answers
JavaFX enters a young and burgeoning RIA marketplace.Will it survive? Will it become the UI scripting language of choice especially for Java developers? It is still too early to make that prediction. However, given its ties to Java and the ability to take RIAs beyond the desktop browser into mobile and consumer devices without rewrites is an attractive offering worthy of exploration and careful study today with possible implementation contemplation tomorrow.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist