La popularidad de Flash hace que sea un nicho apetecible para la competencia de Adobe. Así, han surgido otras alternativas que pretenden hacerse un hueco en el mercado: Microsoft ha lanzado Silverlight. Los desarrolladores de Flash no van a cambiar de plataforma sino perciben una razón convincente. Al lanzar Silverlight Microsoft ofreció a los desarrolladores gráficos a pantalla completa que utilizaban la GPU (tarjeta de aceleración gráfica). Adobe tomó nota y ofrecerá esta caracteristica en la próxima release de Flash.
En este artículo (escrito en Marzo de 2009) veremos que características ofrece JavaFX y como se posiciona frente a sus competidores (Adobe Flash y Microsoft Silverlight). Aunque la primera release oficial JavaFX 1.5 (Marina) estará disponible en Junio de 2009, actualmente podemos ya trabajar con Java FX 1.1.
Lenguaje JavaFX Script
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];
En JavaFX no es obligatorio declarar el tipo una variable en su declaración. Así, podemos escribir el fragmento anterior de la siguiente forma:
var x = 0.9; var name = "David"; var y = 0; var flag = true; var numbers:Number = [1,2,3,4,5];
Los operadores de Java &&, || y ! tienen su equivalente en JavaFX: and, or y not. Por ejemplo:
(5 ==5 and 6 ==6 ) // retorna true
if ( codebase == "" or codebase.startsWith("file:") )
not (5 == 4) // => true
El manejo de arrays se simplifica con las facilidades que incorpora el lenguaje:
def days = ["Lunes","Martes","Miercoles","Jueves","Viernnes","Sab","Dom"];
println(days[0]); // Lunes
println(days[1]); // Martes
println(days[2]); // Miercoles
println(days[3]); // Jueves
println(days[4]); // Viernes
println(days[5]); // Sab
println(days[6]); // Dom
x = [1,2,3];
insert 10 as first into x; // ->[10,1,2,3]
insert 6 after x[. == 2]; // => [10,1,2,6,3]
println(" {sizeof days}); // => 7
var nums = [1..5];
reverse nums; // => [5, 4, 3, 2, 1]
A diferencia de Java, JavaFX soporta blocks. Los blocks (tambien llamadas closures) son muy populares en lenguajes de scripting como SmallTalk o Ruby, permiten realizar una select sobre un array con una sintaxis muy compacta. Veamos un ejemplo:
var lista = [1,2,7,3,30,15,14,6,4];
var menores_de_10 = lista[n|n < 10]; //selecciona los numeros menores de 10
println("Resultado: {menores_de_10}"); => 1 2 7 3 6 4
var pares = list[ n | n mod 2 == 0];
println("Pares: {pares}"); // => 2 30 14 6 4
for (i in lista){
if (i < 10) print(i)
} // => 1 2 7 3 6 4
DireccionPostal {
var calle: String;
var ciudad: String;
var provincia: String;
var codigoPostal: String;
function print() {
println("Calle: {calle} Ciudad: {ciudad} Provincia: {provincia} CodigoPsotal: {codigoPostal} ");
}
}
var direccionPostal = DireccionPostal {
calle: "Avenida de Logroño"
ciudad: "Madrid"
provincia: "Madrid"
codigoPostal: "28042"
}
println (direccionPostal.print()) ;
function addN(n: Number): function(:Number): Number {
function(x: Number): Number { x + n }
}
var addTen = addN(10);
println(addTen(3)); // => 13.0
Manos a la obra
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <rss version="2.0" xmlns:yweather="http://weather.yahooapis.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"> <channel> <title>Yahoo! Weather - Sunnyvale, CA</title> <link>http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/ *http://weather.yahoo.com/forecast/94089_f.html</link> <description>Yahoo! Weather for Sunnyvale, CA</description> <language>en-us</language> <lastBuildDate>Tue, 29 Nov 2005 3:56 pm PST</lastBuildDate> <ttl>60</ttl> <yweather:location city="Sunnyvale" region="CA" country="US"></yweather:location> <yweather:units temperature="F" distance="mi" pressure="in" speed="mph"></yweather:units> <yweather:wind chill="57" direction="350" speed="7"></yweather:wind> <yweather:atmosphere humidity="93" visibility="1609" pressure="30.12" rising="0"></yweather:atmosphere> <yweather:astronomy sunrise="7:02 am" sunset="4:51 pm"></yweather:astronomy> <image> <title>Yahoo! Weather</title> <width>142</width> <height>18</height> <link>http://weather.yahoo.com/</link> <url>http://l.yimg.com/a/i/us/nws/th/main_142b.gif</url> </image> <item> <title>Conditions for Sunnyvale, CA at 3:56 pm PST</title> <geo:lat>37.39</geo:lat> <geo:long>-122.03</geo:long> <link>http://us.rd.yahoo.com/dailynews/rss/weather/ Sunnyvale__CA/* http://weather.yahoo.com/ forecast/94089_f.html </link> <pubDate>Tue, 29 Nov 2005 3:56 pm PST</pubDate> <yweather:condition text="Mostly Cloudy" code="26" temp="57" date="Tue, 29 Nov 2005 3:56 pm PST"></yweather:condition> <description><![CDATA[ <img src="http://l.yimg.com/a/i/us/we/52/26.gif" /><br /> <b>Current Conditions:</b><br /> Mostly Cloudy, 57 F<p /> <b>Forecast:</b><BR /> Tue - Mostly Cloudy. High: 62 Low: 45<br /> Wed - Mostly Cloudy. High: 60 Low: 52<br /> Thu - Rain. High: 61 Low: 46<br /> <br /> <a href="http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/94089_f.html">Full Forecast at Yahoo! Weather</a><BR/> (provided by The Weather Channel)<br/>]]> </description> <yweather:forecast day="Tue" date="29 Nov 2005" low="45" high="62" text="Mostly Cloudy" code="27"></yweather:forecast> <yweather:forecast day="Wed" date="30 Nov 2005" low="52" high="60" text="Mostly Cloudy" code="28"></yweather:forecast> <guid isPermaLink="false">94089_2005_11_29_15_56_PST</guid> </item> </channel> </rss>
De esta respuesta solo nos interesan dos datos. Para obtener la hora del amanecer y del ocaso, buscaremos el nodo <yweather:astronomy> y recogeremos los valores (señalados en negrita) de los atributos sunrise y sunset. JavaFX puede realizar esta tarea facilmente con la clase javafx.io.http.HttpRequest, que modeliza una petición, y javafx.data.pull.PullParser un parseador.Para poder personalizar la aplicación al lugar donde vivimos simplemente adaptaremos la petición GET. Esta petición contiene dos partes, una URL base que es siempre la misma:
http://weather.yahooapis.com/forecastrss?p=SPXX0050&u=c
|
Nota. Para obtener el codigo de localidad correspondiente a la ciudad donde vives podemos consultar en la página Weather Yahoo . Allí introducimos el nombre de nuestra ciudad en la casilla de búsqueda. En la pàgina resultante, la parte final de la URL corresponde al código que necesitamos. Por ejemplo si buscamos el código correspondiente a Sabadell:
|
var url = "http://weather.yahooapis.com/forecastrss?p=SPXX0050&u=c";
def sceneWidth = 425; def sceneHeight = 300; var amanecer: String; //hora del amanecer var ocaso: String; // hora del ocaso
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();
}
}
}
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
}
]
}
}
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
}
}
Despliegue de aplicaciones JavaFX: Standalone, applet y mobile
- Como un applet WebStart integrado dentro del navegador (Web Start Execution)
- Como una aplicación para un telefono movil compatible con JavaFX (Run in Mobile Emulator)
Conclusiones
Recursos
Galeria de Java FX Samples en el portal de SUN







Comentarios
Dejar un comentario Trackback