
While
RIA (which stands for Rich Internet Application)
is not a very popular acronym
, everybody knows what a Flash app is. Surfing the web we find Flash animations all the time. From simulations of the driving test exam to the operation of the Patriot missile interceptors.
Adobe Flash applications provide a user interface (drag and drop, sound, effects, graphics, animations) that would be very difficult to achieve using HTML and JavaScript, even using high-level libraries like Prototype. Adobe gives developers a programming environment (based on language ActionScript 3) to create Flash applications. This environment is very popular and provides tools to effectively coordinate the work of designers (Adobe Photoshop, Illustrator, sounds) and programmers. Flash applications are also popular among Internet users who do not hesitate to download the browser Flash plug-in.
The popularity of Flash makes it an attractive target for Adobe competition. Thus, alternatives have emerged that aim to put a dent in the market: Microsoft has released Silverlight. Of course, Flash developers are not going to change their platform without a compelling reason. By launching Silverlight Microsoft gave developers a full-screen graphics that used the GPU (graphics accelerator card). Adobe knows that and will offer this feature in the next release of Flash.
Figure1. Flash applications
This article (written in June 2009) will show us the features offered by Java FX and how is positioned against its competitors (Adobe Flash and Microsoft Silverlight).
Although the first official release 1.2 is available right now, important improvements and updates are in the way.
Go ahead to the official website of Java Fx , and download the Netbeans IDE. Once installed the environment, create a project (File>> New Project), we add an FX file (Empty Java FX file) and let's create a first test by dragging a rectangle from the palette 'Basic Shapes" on the editor:
Figure 2. Netbeans IDE
Note that when you release the rectangle, the environment automatically imports all necesary classes. If we execute the project (right click>> Debug) we get a window with no title that contains a rectangle:
Figure3. Execution of a JavaFX project
We did our first test !
We have to take into account some considerations: The language used is not Java but JavaScript FX, a new declarative language that runs onto the Java virtual machine. The reason to use a new language is to simplify the developer's life with a syntax more suitable for multimedia applications. It is a DSL (Domain Specific Language) that specializes in interactive entertainment. Here below the main features of the language.
Java FX Script language
We will now see a summary of the features of the Java FX Script language. For a broader view is recommended to consult the excellent tutorials from Sun.
The language incorporates the following basic types: String, Boolean, and Number. Variables are declared using the var keyword. Consider the following examples:
var x: Number = 0.9;
var name: String = "David";
var y: Integer = 0;
var flag: Boolean = true;
var numbers: Number = [1,2,3,4,5];
It is not mandatory to declare a variable type in its declaration. Thus, we can write the above lines as follows:
var x = 0.9;
var name = "David";
var y = 0;
var flag = true;
var numbers = [1,2,3,4,5];
Java operators == and ! have their equivalent in JavaFX:
(5 == 5 and 6 == 6) // => returns true
if (codebase == "" or codebase.startsWith ( "file:"))
not (5 == 4) // => true
Array handling is very intuitive:
def days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sat", "Sun"];
println (days [0]) // Monday
println (days [1]) // Tuesday
println (days [2]) // Wednesday
println (days [3]) // Thursday
println (days [4]) // Friday
println (days [5]) // Saturday
println (days [6]) // Sunday
x = [1,2,3];
insert 10 as first into x ; // => [10,1,2,3]
insert 6 after x[. == 2]; // => [10,1,2,6,3]
To determine the size of the sequence use the
sizeof keyword:
println ( "{sizeof days}"); // => 7
We can reverse a sequence:
var nums = [1 .. 5];
reverse nums; // => [5, 4, 3, 2, 1]
Unlike Java, JavaFX supports
blocks. Blocks (also called closures) are very popular in scripting languages such as Smalltalk or Ruby, to perform a select on an array with a very compact syntax. Here is an example:
var list = [1,2,7,3,30,15,14,6,4];
var less_than_10 = list [n | n <10]>
println ( "Result: (menores_de_10)") => 1 2 7 3 6 4
var even = list [n | n mod 2 == 0];
println ( "Even: (even)") / / => 2 30 14 6 4
You can write an equivalent expression:
for (i in lista){ if (i <> 1 2 7 3 6 4
To create a class that models a postal address (with the attributes
Street,
City,
State,
ZipCode and a method
print() to print a representation of the object) type:
Instantiating an object of class PostalAddress is as simple as:
var postalAddress = PostalAddress {
street: "Loop street "
city: "Los Angeles"
state: "California"
zipCode: "28042"
)
Unlike Java, JavaFX functions are
first class entities. What does this mean? Very simple, with Java FX we can do things that were previously impossible in Java like passing a function as a parameter to another function . Here is an example:
function addN(n: Number): function(:Number): Number {
function(x: Number): Number { x + n }
}
var addTen = addN(10);
println(addTen(3)); // => 13.0
Let's study the code above: Attention to the signature of the addN () function . This function accepts a parameter of type Number and returns a function with signature
function (: Number).
In the next line, the function resulting from addN (10) is assigned to the variable addTen. addTen variable is a function that can be invoked like any other function. Later in the sample code we'll use this feature of JavaFX.
Time to put your feet up
In the light of the main features of the language we can write an example application. We want an application that informs the user of sunrise and sunset time in our city. The final application looks like this:

Let's see step by step how to build the application. First we need the data with sunrise and sunset times.
To obtain these data we will use a Web Service from Yahoo: Yahoo Weather Web Service. A client can launch a GET request against the service and get a XML like the following figure:

Figure 4. XML reponsse from Yahoo
From this response we are interested in only two figures. For the sunrise and sunset time, look for the node <(marked in bold) and get the attributes of sunrise and sunset. Java FX can easily perform this task with the class javafx.io.http.HttpRequest , who modeled a request and a parser javafx.data.pull.PullParser. To be able to customize the application to where we simply adapt the GET request. This request contains two parts, a base URL:
http://weather.yahooapis.com/forecastrss?
and two parameters:
p = SPXX0050 to indicate the location (in this case Barajas) and
u = c where we want to show the temperature units in Celsius degrees
In our case (Barajas), the GET request is as follows:
http://weather.yahooapis.com/forecastrss?p=SPXX0050&u=c
Note. To obtain the location code corresponding to the city where you live can be found on page Yahoo Weather. Here we introduce the name of our city in the search box. On the resulting page, the final part of the URL for the code we need. For example if we want the code for Sabadell city:

Click the GO button and we get the following page:
Therefore, the code for this location is p = SPXX0066.
|
|---|
Thus, we created a new JavaFX class that we call Main.fx. First we declare a String :
var url = "http://weather.yahooapis.com/forecastrss?p=SPXX0050&u=c";
We also declare other variables we'll use later:
def sceneWidth = 425;
def sceneHeight = 300;
var amanecer: String; //sunrise time
var ocaso: String; // sunset time
sceneWidht and sceneHeight variables are defined as constants (def) . The width and height of the application depends on the number of pixels of the bitmap graphics and will not change during execution. On the other hand sunrise and sunset will be modified during the life of the application, and therefore must use var.
We also declare an instance of HttpRequest that models the Yahoo Web service:
HttpRequest {
location: url
onDone: function() {
print ("done");
// Para simular un web service lento
Thread.sleep(1000);
resultado = " Amanecer: {amanecer} \n Ocaso: {ocaso}" ;
}
onInput: function(input) {
try {
PullParser {
input: input
onEvent: function(event) {
if ((event.type == PullParser.START_ELEMENT) and (event.qname.prefix == "yweather")) {
if (event.qname.name == "astronomy") {
amanecer = event.getAttributeValue(QName{name: "sunrise"
});
println("amanecer = {amanecer}");
ocaso = event.getAttributeValue(QName{name: "sunset"
});
println(" ocaso = {ocaso}");
}
}
}
}.parse()
} finally {
input.close();
}
}
}
Note that the HttpRequest class has the callback method onInput() will be activated once the client receives a response from the web service. Since the web service returns an XML, use the class PullParser to parse this response. To parse the response, find the node "yweater" and once found retrieve attribute values sunrise and sunset. This way we obtain the values desired. It is important to note that the class PullParser, the method is a callback function onEvent When you initialize the class PullParser at callbalck onEvent we assign a function to detect events parsing (starting XML node, end node XML). The definition of the graphical elements is easy. So to set the upper rectangle wrote:
var topRectangle: Rectangle = Rectangle {
translateX: 0
translateY: 10
width: sceneWidth - 2
height: 60
stroke: Color.DARKBLUE
strokeWidth: 1
arcWidth: 32
arcHeight: 32
fill: LinearGradient {
endY: 0
stops: [
Stop {
offset: 0
color: Color.DARKBLUE
}
Stop {
offset: 1
color: Color.LIGHTBLUE
}
]
}
}
To get a fill with a linear gradient, we use the class LinearGradient. The horizontal gradient begins with a dark blue and ends in a light blue.
Finally, we models all the graphical elements using the following code:
Stage {
title: " Amanecer y Ocaso en Barajas "
width: sceneWidth
height: sceneHeight
style: StageStyle.TRANSPARENT
scene: Scene {
width: sceneWidth
height: sceneHeight
content: Group {
content: bind [ topRectangle, text, rightRectangle, textResult, bottomRectangle, solView ]
clip: Rectangle {
width: sceneWidth
height: sceneHeight
arcWidth: 32
arcHeight: 32
}
}
fill: Color.TRANSPARENT
}
}
You can see the complete code of the application. You can also run the application by clicking the next link 
JavaFXDeployement
All projects about data can be displayed in three ways:
- As an application (Standalone)
- - As a WebStart applet integrated within the browser (Web Start Execution)
- - As an application for a cell phone compatible data centers (Run in Mobile Emulator)
To choose one of three deployments are going to project properties and select the Run tab, Model Execution (Execution Standart, Run or Run in Browser in Mobile emulator).
Figure. Deployment of a JavaFX application
If you choose the wireless deployment you will have to use the emulator included in the platform (the first JavaFX phoneswill be the ones from LG and Sony-Ericsson in June 2009):
Figure. JavaFX emulator for mobile phone
Conclusions
Java FX Script is a declarative language, statically typed, object oriented and functional. Is designed specifically for writing graphical applications. The development kit provides a comprehensive multimedia library. The war to attract advanced users of ActionScript 3 (Adobe Flash) has begun, but this time Sun has a good arsenal.
Resources
JavaFX samples gallery
JavaFX 1.2 documentation