En Ru
Business Applications
       based on JavaFX

JavaFX for Business Applications

02.02.2009
    
We have tested JavaFX technology and decided to provide you with a review of JavaFX as a foundation for RIA-based business application development, its positive and negative sides. The article also contains a description of most interesting and powerful features of JavaFX Script (a core language for JavaFX-based development) with short code examples.
   
 References:

  JavaFX Technology Hub

  JavaFX Home

  Chris Oliver's JavaFX weblog

  InsideRIA online community

JAVAFX AS RIA PLATFORM FOR BUSINESS SOFTWARE

Sun has finally released the first version of JavaFX platform on Dec 04, 2008. This platform is Sun’s answer to RIA (Rich Internet Applications) platforms like Microsoft Silverlight and Adobe Flex.
JavaFX is a rich client platform for building cross-device applications and content. Designed to enable easy creation and deployment of rich internet applications (RIAs) with immersive media and content, the JavaFX platform ensures that RIAs look and behave consistently across diverse form factors and devices.
It includes a runtime and a tools suite that web scripters, designers, and developers can use to quickly build and deliver rich Internet applications for desktop, mobile devices, TV, and other platforms.

At first glance JavaFX looks fine for development of media-oriented software (audio/video-enabled applications, games, etc.). But the traditional and main market for Java technologies is real business applications. So what is the place of JavaFX in the development of enterprise software?

One possible answer to this question is found in a range of business applications that actively use data visualization, namely:
  • JavaFX-based digital dashboards for Business Intelligence. JavaFX graphic features can be used to implement different kinds of interactive real-time updated charts and graphs (user changes reporting parameter and see the changes on a diagram immediately).
  • JavaFX-based planning and scheduling software. JavaFX can be used to implement graphic-based interactive user interface for handling different types of time-tables and schedules.
  • JavaFX-based online reporting. JavaFX can be used to display diagrams and charts online.


JAVAFX PERSPECTIVES


The idea of RIA platform is not new. It is already implemented by Adobe and Microsoft. Adobe provides mature Flex platform with a wide set of development tools, frameworks, etc. On the other hand Sun released its solution in RIA area quite late and it still requires a lot of work. Does JavaFX have a future in such a conditions?
 
I would say yes. Why? See my suggestions below:
  • JVM-base. JavaFX apps are running inside Java Virtual Machine. That means JavaFX shares all performance and security capabilities of Java runtime.
  • W.O.R.A concept. Write One Run Anywhere concept that allows minimizing development costs and enlarging the potential marketplace. Sun positions JavaFX as a technology that would allow creating cross platform rich GUI internet applications. Potentially JavaFX applications will run on any desktop, browser, mobile device or any other device that runs the Java Runtime Environment.
  • JavaFX Script. New language which is a mix of declarative statements for defining View layouts and procedural/imperative control statements. It allows splitting the development of static and dynamic part of UI. This should increase independency between designers and programmers and let the later to concentrate on business-logic and technical stuff while the first ones take care about look-and-feel.
  • Easy access to Java. Makes JavaFX attractive to huge Java-developer community and greatly simplifies creating business and technical back-end for RIAs. It is also greatly simplifies extending existing Java-based enterprise business applications with a set of features typical for RIAs.
What are the possible barriers for JavaFX? Here are my suggestions:
  • Additional runtime environment is required. It makes JavaFX less user-friendly. Different RIA platforms require different runtime environments. This fact can become a nightmare for end-users. On the other hand interactive Web-applications built with pure Ajax/JavaScript capabilities don’t have such a limitation. If the user has a choice between an application that requires installing additional software and an application that requires only a browser I believe he selects the second one. However Ajax is not a panacea I think: It is less development-friendly and its capabilities are quite strict for rich application development.
  • Lack of tools. Currently JavaFX provides so called JavaFX Productions Suite (a suite of tools and plug-in for creative tools that allows graphical assets to be exported to JavaFX applications) and NetBeans IDE 6.5 plug-in for JavaFX 1.0 (provides an integrated development environment for building, previewing, and debugging JavaFX applications). However their current capabilities are quite limited (e.g. JavaFX applications can be exported from Adobe Photoshop/Illustrator but can not be imported, NetBeans does not have visual layout-editor for JavaFX).
  • Limited platform support. Despite the fact that JavaFX is positioned as a unified development and deployment platform for building RIAs across desktop, browser and mobile for now JavaFX 1.0 applications will run on any Windows or Mac OS X desktop running Java 1.5 or higher. Linux and Solaris platforms are not yet officially released as well. This greatly decreases the area of potential receivers. However it seems to be a temporary problem.
  • Maturity. JavaFX relative maturity compared to the Silverlight and especially Flex is quite low. JavaFX is lacking some important common UI-components. For example there is no kind of data grid component. That would require developers to wrap Java JTable and program to it. So JavaFX developers should still have a background of a Java Swing programmer, which will be an obstacle for many Java developers. This also makes JavaFX less attractive to use for development of data-base front-end applications which is a typical case for business applications. The list of custom frameworks for JavaFX is also quite short for now. But keep in mind the fact that JavaFX is still 1.1 and the platform is being actively elaborated and extended.


JAVAFX SCRIPT. KEY FEATURES OVERVIEW


The core of JavaFX development is JavaFX Script.
JavaFX Script is a compiled (it called a “script” but it is not an interpreted language), statically typed (types are being checked during compilation), declarative language for the Java Platform. It provides automatic data-binding, mutation triggers and declarative animation, using an expression language syntax (all code blocks potentially yield values.) Many classes of the JavaFX Script are designed for implementing Swing and Java 2D functionalities more easily. With JavaFX Script you can develop GUIs, animations, and different effects for text and graphics using only a few straightforward lines of code. This should greatly reduce development efforts for UI-part of business applications.
Because of the fact that JavaFX is built on top of the Java Platform, it is easy to use Java classes in JavaFX Script code. Compiled JavaFX Script is able to run on any platform which has a recent Java Runtime installed.

Declarative Syntax

JavaFX Script declarative syntax for constructing user interfaces contrasts with the more verbose series of method calls required to construct an equivalent interface in Java Swing directly.

Here is a simple Hello world program for JavaFX Script:

import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
 
Stage {
  title: " Hello, World!"
  width: 250
  height: 70
  scene: Scene {
          content: [
              Text {
                 content: "Hello, World!"
                 x:0
                 y:12
            }
          ]
  }
}


For example the same program written in Java Swing looks like this:

import javax.swing.JFrame;
import javax.swing.JLabel;
public class HelloWorld {
 
    public static void main(final String[] args) {
       JFrame frame = new JFrame("Hello, World!");
       frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
       frame.add(new JLabel("Hello, World!"));
       frame.pack();
       frame.setVisible(true);
    }
}


As you can see the program written in JavaFX is more designer-friendly. The designers do not need to look deep into the implementation details to build a user interface. They are just defining a set of components with a set of attributes. The behavior of these components can be customized by programmers later.

Data binding

Data binding is the ability to create an immediate and direct relationship between two variables (you often need to update one variable whenever another variable changes). It is one of the most useful and powerful features of the JavaFX Script programming language.
 
Data binding simplifies creating interactive user interface. For example you are changing the value of one component and the second one is being updated automatically.
Here is a simple program that demonstrates data binding capabilities. The program intended to change project budgets and show budget values as a bar chart (see the screenshot below).
 
Picture: Initial bar chart state
Figure 1 – Initial bar chart state

Picture: User moves slider and bar chart is being updated
Figure 2 – User moves the slider (changes project budget value) and the bar chart is being updated

This simple showcase has the following implementation:

package javafxbarchart;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.ext.swing.SwingSlider;
import javafx.geometry.Rectangle2D;

// Bar Cart Bottom position
def barBottom = 180;
//defining Swing Slider components to change projects' budget values
var project1Budget = SwingSlider { minimum: 0, maximum: 100000, value: 30000,
    vertical: false, impl_layoutX: 10, impl_layoutY: 13}
var project2Budget = SwingSlider { minimum: 0, maximum: 100000, value: 75000,
    vertical: false, impl_layoutX: 10, impl_layoutY: 45}
//binding bar heights to projects' budget values
var project1BarHeight = bind project1Budget.value / 1000;
var project2BarHeight = bind project2Budget.value / 1000;
//binding top Y position to bar height
var yPosProject1 = bind ( barBottom - project1BarHeight);
var yPosProject2 = bind ( barBottom - project2BarHeight);
//defining chart bar to display budget value for the first project
var chartBarProject1 = Rectangle { x: 40, width: 70,
                height: bind project1BarHeight,
                fill: Color.RED
                y: bind yPosProject1}
//defining chart label to display budget value for the first project
var project1BudgetLabel = Text { font: Font {size: 12},x: 50,
                //binding label caption to top Y bar position
                y: bind yPosProject1 - 5,
                //binding label caption to projectBudget value
                content: bind "{project1Budget.value} eur"}
... //similar definition for chart bar and label for the second project
Stage {
    title: "Project Budgets"
    width: 230
    height: 240
    scene: Scene {
        content: [
          //Sliders
          project1Budget, project2Budget,
          //Labels
          Text {font: Font {size: 12}, x: 70, y: 12,content: "Project 1 Budget"},
          Text {font: Font {size: 12}, x: 70, y: 45,content: "Project 2 Budget"},
          Text {font: Font {size: 12}, x: 40, y: barBottom + 10,
                content: "Project 1"},
          Text {font: Font {size: 12}, x: 110, y: barBottom + 10,
                content: "Project 2"}
          //Bar Chart
          chartBarProject1,
          project1BudgetLabel,
          chartBarProject2,
          project2BudgetLabel,
        ]
    }
}


Moreover, JavaFX script provides a triggering mechanism that allows binding custom behavior to variable value changes. JavaFX script introduces Replace Triggers that are arbitrary blocks of code that attach to variables and execute whenever the variable's value changes. According to the documentation, JavaFX triggers operate the same manner as SQL triggers.
Here is an example that shows the basic syntax: it defines a reportingYear variable and attaches a replace trigger to it. When the value of the reportingYear variable is being changed, the trigger prints out a message displaying its new value, validates that new value is greater then the minimal possible (2000) and sets it to the minimal value if validation is failed:

var reportingYear = 2008 on replace oldReportingYear {
println("\Changing reporting year from {oldReportingYear} to {reportingYear}");
  if (reportingYear < 2000){
    println("\Reporting year is less then minimal available. Setting reporting year to 2000...");
    reportingYear = 2000;
  }
};


Triggers allow handling data modification events in an aspect-like fashion. The bind keyword allows bidirectional binding between two variables so that when one receives an update the other also gets updated. Using these two concepts simplifies handling modification events of UI elements and variables comparing to Java language.
A typical application workflow were triggering and binding are very useful is automatic refreshing of graphic-based reports. For example the user changes reporting year via a drop-down list in your JavaFX-based financial application. New report data is being obtained from the database automatically by calling of the corresponding function from the replace trigger. JavaFX-based diagram intended to display the price history report data has a set of data attributes that are bound to report data variables. Therefore when the report data is being updated by replace trigger JavaFX diagram are being refreshed automatically. There’s no need to implement any notification and listening mechanism like in pure Java. Therefore JavaFX implementation of such functionality would be quite simple and transparent comparing to implementation in pure Java.

Access to existing Java libraries

JavaFX script allows using existing Java libraries. Java code can be accessed by calling the constructor of the Java classes and their methods in JavaFX Script in the same way as one would in a pure Java.
The following program demonstrates how to use Java capabilities at JavaFX script. It simply shows a User email address for the selected User.

package javaobjects;

import javafx.ext.swing.SwingComboBox;
import javafx.ext.swing.SwingComboBoxItem;
import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
//importing Java libraries
import dataservices.User;
import dataservices.UserService;


var userEmail; //label content
/*binding variable to combobox selected item index in order automatically proccess
 selection changes */
var selectedUserNameIndex = bind userNameCombobox.selectedIndex on replace oldIndex {
    /*calling Java code. UserService is Java class.It can implement complex
     data acess logic (for example search in DataBase, remote call, etc.)*/
    def user = UserService.findUserByName(userNameCombobox.selectedItem.text);
    //calling method of Java object to evaluate new label content
    userEmail = user.getEmail()
}

//combobox for selecting a user name
var userNameCombobox = SwingComboBox {
    items: [
        SwingComboBoxItem{
        text:"User1"},
        SwingComboBoxItem{
        text:"User2"},
        SwingComboBoxItem{
        text:"User3"}
    ]
    selectedIndex: 0
    width: 100;

}
Stage {
    title: "Accessing Java Objects"
    width: 340
    height: 150
    scene: Scene {
        content: [
            Text {
                font: Font {
                    size: 12
                }
                x: 105
                y: 20
                //binding to variable for automatic update of label content
                content: bind "Email adress: {userEmail}" ;
            },
            userNameCombobox
        ]
    }
}


Such a feature greatly enhances JavaFX-based development since it opens an access to all Java capabilities (RMI, database access, etc.). This is especially useful when you need to enrich your existing business application with data visualization capacities provided by JavaFX. For example if you have some kind of financial application written in Java and you want to enrich it with digital dashboard for graphic-based reports. You can use JavaFX charts to display historical diagrams, pie-charts, etc.  JavaFX may be the right choice in this case.

Usage of JavaFX objects in Java.

JavaFX can directly call Java code without any problem. However, the reverse is not supported by JavaFX.
Do developers have the need of such kind of interaction between Java and JavaFX? I would say yes.  Just consider the MVC (Model-View-Controller) design pattern, we can write an application using Java and JavaFX together. The Model and Controller part can be implemented with Java while the View can be done by JavaFX.
 
The most flexible approach to create JavaFX objects is to use the Script engine that is part of the compiler. It allows parsing and executing JavaFX Script on-the-fly. A script can be passed as a text file or as a string argument.
The following example will pass a string argument to create a JavaFX object: It shows a simple JavaFX class with one attribute property and a single method, printValue().
 
CustomJavaFXClass.fx
import java.lang.System;
public class CustomJavaFXClass {

    public attribute value: String;

    public function printValue(){
        System.out.println(value);
    }
}

 
Constructing CustomJavaFXClass in Java program
import javax.script.ScriptEngineManager;
import com.sun.javafx.api.JavaFXScriptEngine;

public class Main {

  public static void main (String[] args) {
    ScriptEngineManager manager =
        new ScriptEngineManager();

    JavaFXScriptEngine fxEngine =
        (JavaFXScriptEngine) manager.getEngineByName("javafx");

    try {

      String param = "JavaFX object created in Java";

      String script = String.format (
          "CustomJavaFXClass {value: \"%s\"}", param);

      Object fxObject = fxEngine.eval(script);

      fxEngine.invokeMethod(fxObject, "printValue");

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}
       
Developers can partially optimize this approach using the fact that JavaFX classes are able to implement Java interfaces just like Java classes. This can be used to allow Java objects to access JavaFX objects as they would access any other implementation of an interface.
 
Interface
public interface IPrintableValue {
  public void printValue();
}


CustomJavaFXClass.fx
public class CustomJavaFXClass extends IPrintableValue

In Java program
String script = String.format ("CustomJavaFXClass {value: \"%s\"}", param);

IPrintable fxObject = (IPrintableValue) fxEngine.eval(script);
fxObject.printValue();


However, on my point of view, calling JavaFX script with the generic script engine API feels like workaround. It looks like calling methods via reflection all the time and such code is hard to maintain and debug. Official way to instantiate JavaFX objects in Java would be a much more powerful solution. JavaFX is already byte code so why isn’t there any official way to instantiate JavaFX objects? Hope such a feature will be available in future.

Integration with JavaScript

JavaFX applets run in the browser with the help of the Java browser plug-in that provides the LiveConnect API Bridge for JavaScript. LiveConnect allows applets to call into JavaScript methods on the page from JavaFX Script and similarly allows JavaScript to call into JavaFX Script methods of an applet.
 
Next sample code shows how to access JavaFX-applet functions via JavaScript:

customApllet.Main.fx:
public function updateView():void {

  //updating application content
}


customPage.html:
<applet code=" customApllet.Main" width="600" height="300" id="appl" />
<script>
function updateView() {
var appl = document.getElementById("appl");
appl.script.updateView();
}
</script>



REFERENCES

  1. JavaFX Technology Hub
  2. JavaFX Home
  3. Chris Oliver's JavaFX weblog
  4. InsideRIA online community


If you are interested to get our proposal for development based on JavaFX or on other Java technology please send us your request.

Photo: Elena Popretinskaya, CTO
  Posted by Elena Popretinskaya,
  CTO
Bookmark or share:
Digg Stamble Upon Facebook Technorati Twitter Mr. Wong GoogleLinkedIn Delicious