ejemplo simple de animación javafx

Upload: fracobx19

Post on 06-Apr-2018

238 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    1/42

    Ejemplo simple de animacin JavaFX

    Este es un ejemplo sencillo de lo que se puede hacer con JavaFX, en esta aplicacingeneramos una animacin simple con transparencia en la ventana, veremos tambin que paralograr esto bastaran adicionar o configurar un par de instrucciones, como siempre JavaFX nos

    permite hacer muchas cosas con poco cdigo.

    Para la animacin solo utilizamos un alinea de tiempo y tres objetos, dos crculos y un texto.Para los crculos solo cambiamos es radio y para el texto cambiamos la opacidad en laanimacin.

    Aqu mostramos parte del cdigo, especficamente la parte de la animacin.

    Timeline {keyFrames: [KeyFrame { time: 1s values: radio => 150 tween Interpolator.EASEBOTH },KeyFrame { time: 2s values: radio2 => 200 tween Interpolator.EASEBOTH },KeyFrame { time: 2s values: opacidad => 1 }]autoReverse: truerepeatCount: Timeline.INDEFINITE}

    Ahora podemos descargar el cdigo completo, el ejecutable y el proyecto en IDE NetBeans.

    Cronmetro en JavaFX

    Preparando en el entorno de desarrollo

    Siga estos pasos para preparar el entorno de desarrollo para JavaFX Script:

    Descargue e instale JDK 6u1 with NetBeans 5.5.1

    http://java.sun.com/javase/downloads/netbeans.htmlhttp://java.sun.com/javase/downloads/netbeans.htmlhttp://java.sun.com/javase/downloads/netbeans.htmlhttp://lh5.ggpht.com/_Fpu5xMERI_U/TNYiHvdgwII/AAAAAAAAADw/BLLYEcoL5nU/s1600-h/AnimacionSIYAM[2].pnghttp://java.sun.com/javase/downloads/netbeans.html
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    2/42

    Instale JavaFX plug-in desde el manejador de paquetes de NetBeans

    Antes de agregar algn componente, descargue los complementos de la aplicacin JavaFX Assetssource code y extraiga su contenido en la carpeta assets en la carpeta "src" en donde estrealizando el proyecto de NetBeans

    JavaFX Script no tiene un tipo de proyecto especial, entonces para empezar, solamente cree unproyecto regular Java usando File->New Project desde el men (vea figura 2)

    Figura 2. Nuevo Proyecto

    El proyecto estar vaco. Ingrese stopwatch como nombre de proyecto, desmarque CreateMain Class y haga clic en Finish (la figura 3 muestra el result ado)

    http://java.sun.com/javase/downloads/netbeans.htmlhttp://java.sun.com/javase/downloads/netbeans.htmlhttps://openjfx.dev.java.net/javafx-nb55-plugin-install.htmlhttps://openjfx.dev.java.net/javafx-nb55-plugin-install.htmlhttps://openjfx.dev.java.net/javafx-nb55-plugin-install.htmlhttp://assets.devx.com/marketplace/20130.ziphttp://assets.devx.com/marketplace/20130.ziphttp://assets.devx.com/marketplace/20130.ziphttp://assets.devx.com/marketplace/20130.ziphttp://assets.devx.com/marketplace/20130.ziphttps://openjfx.dev.java.net/javafx-nb55-plugin-install.html
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    3/42

    Figura 3. Nombre de proyecto

    A continuacin haga clic en y seleccione New->File/Folder (vea la figura 4para detalles). La prxima vez que agregue un archivo, la opcin JavaFX File debera apareceren el men debajo de New.

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    4/42

    Figura 4. Agregando un archivo JavaFX

    Ahora usted tiene un proyecto JavaFX vaco. Para habilitar la opcin de ejecutar el proyecto,haga clic con el botn derecho sobre el nombre de proyecto y elija Properties. Seleccione

    Other de la lista de categoras, elija JavaFX File como el tipo de archivo y haga clic en Next.Ingrese stopwatch como el nombre de archivo y haga clic en Finish (vea la figura 5 paradetalles)

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    5/42

    Figura 5. Agregando el archivo JavaFX

    Para establecer el archivo de JavaFX como principal, en Project Properties, ingrese stopWatch en el campo Arguments en la solapa Run y haga clic en OK (la figura 6 muestra losresultados)

    Figura 6. Estableciendo el archivo principal JavaFX en las propiedades del proyecto

    Ahora escriba el siguiente cdigo en el archivo stopWatch a modo de ejemplo para ver laejecucin de una pequea aplicacin.

    import javafx.ui.*;import javafx.ui.canvas.*;

    Frame {title: "StopWatch"width: 260, height: 280content: []visible: true}

    Presione F6 para ejecutar la aplicacin (la figura 7 muestra el resultado)

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    6/42

    Figura 7. Aplicacin JavaFX bsica

    Construyendo la interfaz de usuario UI

    Primero descargue los complementos de la aplicacin JavaFX Script code y extraiga su contenidoen la carpeta assets en la carpeta en donde est realizando el proyecto de JavaFX. Acontinuacin, haga que se muestre el fondo del cronometro y los botones agregando el siguientecdigo dentro de las llaves del atributo Frame:

    Canvas {background: whitecontent:[

    // BackgroundImageView {transform: [Translate {x: 5, y: 5} ]image: Image { url: "assets/sport_bg.png" }},

    // Start / Stop buttonImageView {transform: [Translate {x: 197, y: 16.85} ]image: Image { url: "assets/start_btn.png" }},

    // Clear buttonImageView {transform: [Translate {x: 190.5, y: 193.35}]image: Image { url: "assets/clear_btn.png" }},]}

    Usted usar el objeto Canvas para crear un espacio en el cual usted puede mostrar grficos.ImageView muestra imgenes bitmap (observe como el atributo transform es usado paraposicionarlo)

    Ejecute la aplicacin para verificar que se muestra el fondo y los botones. Desafortunadamente,Java y JavaFX Script no ofrecen una manera fcil de soportar ventanas transparentes. Ademstendr que convertir las agujas del cronometro en un formato vectorial que JavaFX reconozca.

    http://assets.devx.com/sourcecode/20130.ziphttp://assets.devx.com/sourcecode/20130.ziphttp://assets.devx.com/sourcecode/20130.ziphttp://assets.devx.com/sourcecode/20130.zip
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    7/42

    Puede encontrar un conversor en lnea, SVG-to-JavaFX converter , naturalmente implementadoen Java.

    Usar el conversor es sencillo, simplemente abra el archivo SVG y el conversor lo transforma enJavaFX Script, lo muestra en pantalla y permite que se grabe el cdigo resultante (vea la figura8 para ver un cronometro mostrado por el conversor)

    Figura 8. Conversor SVG-to-JavaFX

    Los convertidores normalmente crean clases completas, las cuales contienen funciones paraacceder a todas las partes del archivo SVG. Para este ejemplo, usted solamente deber agregarel siguiente cdigo dentro del atributo content del objeto Canvas para que se vean las agujas enel cronmetro

    Group {transform: [Translate{x: 88, y: 158}]content: [Rect {fill: rgba(0x00, 0x00, 0x00, 0xff)opacity: 1,height: 16.488014

    opacity: 1arcWidth: 2*5.8192997arcHeight: 2*8.244007stroke: rgba(0x00, 0x00, 0x00, 0xff)strokeWidth: 0.7759066width: 69.317505x: 0.3879533y: 0.44672397},

    http://blogs.sun.com/chrisoliver/entry/javafx_svg_translator_previewhttp://blogs.sun.com/chrisoliver/entry/javafx_svg_translator_previewhttp://blogs.sun.com/chrisoliver/entry/javafx_svg_translator_previewhttp://blogs.sun.com/chrisoliver/entry/javafx_svg_translator_preview
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    8/42

    Text {x: 6y: 5content: "00:00:00.00"font: Font {faceName: "Arial", size: 11}}]},

    // Seconds handGroup {transform: [Translate{x: 122.38, y: 122.38}]content: [ drawHand() ]},

    // Minutes handGroup {transform: [Translate{x: 122.38, y: 75.65}, Scale{x: 0.286, y: 0.286}]content: [ drawHand() ]},]}

    En este ejemplo drawHand() es una funcin la cual est definida de la siguiente manera:

    function drawHand() = [Group {transform: [matrix(0.4849389, -0.0016326762, 0.0016326762, 0.4849389, -139.12367, -155.46147),]content: [Path {d: [MoveTo {x: 322.0y: 302.86218

    absolute: true},ArcTo {rx: 19.5ry: 19.5xAxisRotation: 0.0largeArcFlag: truesweepFlag: truex: 283.0y: 302.86218absolute: true},ArcTo {rx: 19.5

    ry: 19.5xAxisRotation: 0.0largeArcFlag: truesweepFlag: truex: 322.0y: 302.86218absolute: true},ClosePath {},]

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    9/42

    fill: rgba(0x00, 0x00, 0x00, 0x0)opacity: 0.90196078,stroke: rgba(0x00, 0x00, 0x00, 0xff)strokeWidth: 4.034483transform: [matrix(0.0, -0.7435897, 0.7435897, 0.0, 60.109512, 544.98334),]},Path {d: [MoveTo {x: 285.67114y: 135.86218absolute: true},CurveTo {x1: 281.8207y1: 135.86218x2: 279.5y2: 409.36215x3: 279.5y3: 409.36215smooth: falseabsolute: true},LineTo {x: 292.0y: 409.36215absolute: true},CurveTo {x1: 292.0y1: 409.36215x2: 289.54614y2: 135.86218x3: 285.67114y3: 135.86218smooth: falseabsolute: true},ClosePath {},]fill: rgba(0x00, 0x00, 0x00, 0xff)opacity: 1,fillRule: EVEN_ODDstroke: rgba(0x00, 0x00, 0x00, 0xff)strokeLineCap: BUTTstrokeWidth: 1.0},]}];

    Estas piezas combinadas le dan a usted la interfaz completa de la aplicacin cronometro(stopWatch). Presiones F6 para probar la aplicacin antes de avanzar (vea la imagen 9 para vercomo resulta la ejecucin del cdigo)

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    10/42

    Figura 9. Interfaz previa

    Implementando la Animacin

    JavaFX Script ofrece una forma interesante de implementar interfaces de usuario dinmicas. Usael operador bind, el cual permite asociar una variable o atributo con una cierta expresin, deforma que cada vez que la expresin cambia, el atributo tambin lo hace. Agregue el siguientecdigo justo debajo de de las importaciones y antes del objeto Frame.

    import java.lang.System;import java.lang.Math;

    class stopWatch {attribute _is_running: Boolean;attribute _startTime: Integer;attribute time: Integer;attribute timeString: String;attribute angleMinutes: Number;attribute angleSeconds: Number;attribute timer: Number;operation updateTime();operation start();operation stop();operation clear();}

    attribute stopWatch.angleSeconds = 0.0;attribute stopWatch.angleMinutes = 0.0;attribute stopWatch.timeString = "00:00:00.00";attribute stopWatch._startTime = System.currentTimeMillis();attribute stopWatch.time = 0;attribute stopWatch._is_running = false;

    var watch = new stopWatch();

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    11/42

    Con este cdigo, se declar la clase stopWatch, se asignaron los valores iniciales a los atributos,y se cre una instancia de la clase.

    Ahora se pueden asociar algunos atributos de la siguiente manera:

    Cambie el contenido del atributo Text de "00:00:00.00 a bind watch.timeString . El

    cdigo resultante es:

    Text {x: 6y: 5content: bind watch.timeStringfont: Font {faceName: "Arial", size: 11}}

    Agregue las transformaciones de rotacin a las agujas de los minutos y segundos y unalos ngulos de rotacin a watch.angleSeconds y watch.angleMinutes respectivamente. Elcdigo resultante es:

    // Seconds handGroup {transform: [Translate{x: 122.38, y: 122.38},Rotate{angle: bind watch.angleSeconds}]content: [ drawHand() ]},

    // Minutes handGroup {transform: [Translate{x: 122.38, y: 75.65}, Scale{x: 0.286, y: 0.286},Rotate{angle: bind watch.angleMinutes}]content: [ drawHand() ]},

    Los corchetes denotan una serie de objetos asignados a un atributo, en este caso, se aplicaron

    muchas transformaciones en forma simultnea.

    Modifique los valores iniciales de la clase para observar como la interfaz del cronometro muestrauna desviacin en el ngulo de las agujas. Por ejemplo:

    class stopWatch {attribute _is_running: Boolean;attribute _startTime: Integer;attribute time: Integer;attribute timeString: String;attribute angleMinutes: Number;attribute angleSeconds: Number;attribute timer: Number;

    operation updateTime();operation start();operation stop();operation clear();}

    attribute stopWatch.angleSeconds = 10.0;attribute stopWatch.angleMinutes = 30.0;attribute stopWatch.timeString = "00:00:00.00";attribute stopWatch._startTime = System.currentTimeMillis();attribute stopWatch.time = 0;

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    12/42

    attribute stopWatch._is_running = false;

    var watch = new stopWatch();

    Con estos valores, se observa lo siguiente:

    Figura 10. Variacin en la UI

    Ahora, se necesita un Temporizador . La implementacin del timer requiere agregar un atributo,un disparador y un manejador que contendr el cdigo del disparador. Para esto agregue elsiguiente cdigo debajo del ltimo atributo de inicializacin:

    attribute stopWatch.timer = bind [1..50] dur 1000 linearwhile _is_runningcontinue if true;

    trigger on stopWatch.timer = value {if (_is_running) {time = System.currentTimeMillis() - _startTime;updateTime();}}

    operation stopWatch.updateTime() {var hours: Integer = Math.floor(time / 3600000);var rem: Integer = time % 3600000;var minutes: Integer = Math.floor(rem / 60000);rem %= 60000;var seconds: Integer = Math.floor(rem / 1000);var milliseconds: Integer = rem % 1000;

    angleMinutes = minutes * 30 + seconds * 0.5;angleSeconds = seconds * 6 + milliseconds / 1000 * 6;

    timeString = "{hours format as }:{minutes format as }:{secondsformat as }.{milliseconds/10 format as }";

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    13/42

    }

    El disparador creado, muestra 50 actualizaciones por segundo. La operacin updateTime() usaJavaFX Script para dar formato al display digital. Este operador, soporta formatos siguiendoconvenciones del estilo Java, como ser java.text.DecimalFormat, java.text.SimpleDateFormat,and java.util.Formatter. Las llaves permiten que se ingrese cdigo dentro de strings literales.

    Cambie el valor inicial del atributo _is_runnung a trae y pruebe la aplicacin para ver si eltemporizador funciona

    Aadiendo interactividad

    Antes que nada, agregue las implementaciones para las operaciones start(), stop() y clear():

    operation stopWatch.start() { _is_running = not _is_running;if (_is_running) {

    _startTime = System.currentTimeMillis() - time;} else {time = System.currentTimeMillis() - _startTime;}}operation stopWatch.stop() {

    _is_running = false;clear();}operation stopWatch.clear() {

    _startTime = System.currentTimeMillis();time = 0;updateTime();}

    A continuacin agregue el manejador de eventos para los botones Start/Stop:

    // Start / Stop buttonImageView {transform: [Translate {x: 197, y: 16.85} ]image: Image { url: "assets/start_btn.png" }onMousePressed: operation(event) {watch.start();}},

    // Clear buttonImageView {transform: [Translate {x: 190.5, y: 193.35}]image: Image { url: "assets/clear_btn.png" }onMousePressed: operation(event) {watch.clear();}},

    Para setear un manejador de evento, se debe asignar la operacin necesaria al atributoapropiado del elemento.

    Finalmente, agregue el siguiente atributo al elemento Frame, el cual llama al manejador delevento onClose cuando la ventana es cerrada.

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    14/42

    onClose: operation() {watch.stop();delete watch;}

    Esto asegura que la aplicacin termina en forma correcta y previene de posibles problemas alsalir de la misma. Por otro lado, cuando un usuario cierra la aplicacin mientras esta est siendoejecutada, el thread GUI terminar pero el thread del temporizador se detendr y evitar que seproduzcan errores.

    Implementacin

    El desarrollo de un proyecto JavaFX con NetBeans produce un paquete llamado stopwatch.jar elcual se puede ejecutar con Java Web Start . El proceso requiere de los siguientes pasos:

    Crear el archivo .jar

    jar cvf stopWatch.jar stopWatch.fx

    Crear un archivo JNLP con una descripcin de la aplicacin.

    StopWatchSusana MoralesWeb Start example for JavaFX Scripts

    StopWatch

    Firmar los archivos .jar

    jarsigner -keystore jfx.keystore -verbose -keypass keyPassword -storepass storePasswordstopWatch.jar jfx

    jarsigner -keystore jfx.keystore -verbose -keypass keyPassword -storepass storePassword

    http://java.sun.com/products/javawebstart/http://java.sun.com/products/javawebstart/http://java.sun.com/products/javawebstart/http://java.sun.com/products/javawebstart/
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    15/42

    javafxrt.jar jfx jarsigner -keystore jfx.keystore -verbose -keypass keyPassword -storepass storePasswordswing-layout.jar jfx

    Configurar el servidor web para que reconozca la extension .jnlp

    AddType application/x-java-jnlp-file JNLP

    Publicar el link al archivo .jnlp que usted acaba de subir al servidor web

    Para un demo de la aplicacin, haga clic aqu

    10 MINUTE TUTORIAL - JAVAFX: BASIC 2D GRAPHICS AND ANIMATION

    Update: I have updated this tutorial for JavaFX 1.0JavaFX, due to its declarative syntax, empowers developers with the ability to quickly buildengaging user-interfaces that leverage eye-popping effects and animation to deliver a deeper,more visceral experience. But, you've got to learn to walk before you run so this tutorial willexplore JavaFX's basic animation concepts by creating a simple slide show containing variousshapes. For added fun, each slide will have the ability to rotate. While eye-popping it is not, Ithink this tutorial will give you a good starting point to begin working on more complexanimations.

    Prerequisites All the prerequisites defined in the

    10 Minute JavaFX Tutorial - Develop and deploy JavaFX Applets and Applications whileonline and offline

    QuickStart

    If you want to see the end result of this tutorial and you have installed all the prerequisites, thenplease download the ZIP file below, unzip it and open the shapeslideshow-applet.html file in yourbrowser.

    Shape Slide Show Sample (you may read this software's license here )If you want to see the sample in action right now, use the links below:

    Shape Slide Show JavaFX applet Shape Slide Show JavaFX Webstart application (you may need to save the JNLP file first,

    then open it)

    Step 1: Define the slide show constants

    First, we need to define several constants for the slide show. Create a file named SlideShow.fx

    and put this code in it:

    package com.dieajax.sample.slideshow;

    import javafx.animation.Interpolator;import javafx.animation.KeyFrame;import javafx.animation.KeyValue;import javafx.animation.Timeline;import javafx.animation.transition.RotateTransition;import javafx.animation.transition.TranslateTransition;import javafx.ext.swing.SwingButton;

    http://bubblemark.com/stopwatch/jfx/stopwatch.jnlphttp://bubblemark.com/stopwatch/jfx/stopwatch.jnlphttp://bubblemark.com/stopwatch/jfx/stopwatch.jnlphttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://www.dieajax.com/downloads/tutorial/javafx/slideshow/ShapeSlideShow.ziphttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/software-license&usg=ALkJrhgq0d0tWTbWrtZu5bH_JY0pfvlrKghttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/samples/tutorial/javafx/slideshow/shapeslideshow-applet.html&usg=ALkJrhh75v2TeW382t8qP6yTq7pJ_OC4iwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/samples/tutorial/javafx/slideshow/shapeslideshow-webstart-online.html&usg=ALkJrhhF7yt4SLBqUlwAYCPklgm_w_I1Awhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/samples/tutorial/javafx/slideshow/shapeslideshow-webstart-online.html&usg=ALkJrhhF7yt4SLBqUlwAYCPklgm_w_I1Awhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/samples/tutorial/javafx/slideshow/shapeslideshow-applet.html&usg=ALkJrhh75v2TeW382t8qP6yTq7pJ_OC4iwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/software-license&usg=ALkJrhgq0d0tWTbWrtZu5bH_JY0pfvlrKghttp://www.dieajax.com/downloads/tutorial/javafx/slideshow/ShapeSlideShow.ziphttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://bubblemark.com/stopwatch/jfx/stopwatch.jnlp
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    16/42

    import javafx.scene.Group;import javafx.scene.Node;import javafx.scene.layout.HBox;import javafx.scene.Scene;import javafx.scene.paint.Color;import javafx.scene.shape.Rectangle;import javafx.scene.shape.Ellipse;import javafx.scene.text.Text;import javafx.scene.transform.Rotate;import javafx.scene.transform.Transform;import javafx.scene.transform.Translate;import javafx.stage.Stage;

    def width = 300;def height = 200;

    def slideWidth = 40;def slideHeight = 40;

    def startX = (width / 2) - (slideWidth / 2);def startY = (height / 2) - (slideHeight / 2);

    def nextX = width;def nextY = (height / 2) - (slideHeight / 2);

    I went ahead and added all the imports needed later, so you can ignore them for now. Skippingto the variable definitions , unsurprisingly, the width and height variables define the widthand height of the slide show in pixels.slideWidth and slideHeight denote the width and heightof a slide within the slide show itself. The startX and startY variables represent the upper -leftcoordiante of the first slide shown when the program starts. The upper-left coordinate for therest of the slides, assigned to nextX and nextY, conviently puts the unseen slides off -screen, until brought into view by user later.

    Step 2: Define the slide model

    As I mentioned in in a previous JavaFX tutorial , the unique features of JavaFX really come intoplay when using MVC-like patterns, so this tutorial will model the slide show domain usingclasses. The first class, called SlideModel , will represent a slide itself:

    ...class SlideModel {var x: Number;var y: Number;var rotation: Number;var rotateTransform = Rotate {angle: bind rotationpivotX: bind (x + slideWidth / 2 )pivotY: bind (y + slideHeight /2 )};}

    The x, y and rotation variables simply hold values for the position and rotation of theslide. The javafx.scene.transform.Rotate class represents a 2D rotation transform of a visualnode in the JavaFX scene graph. Note that the Rotate class' variables bind to variables defined inthe enclosing SlideModel class. This means that if the rotation variable in the model getsupdated, the Rotate transform updates, which will then make whatever visual node it applies toappear to spin.

    Learn more about the Rotate class

    http://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2007/09/14/10-minute-tutorial-javafx-event-handling-using-trigger-and-bind/&usg=ALkJrhiiBZs5pZwE-eMc5lCGD-uRVLFy5Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.transform/javafx.scene.transform.Rotate.html&usg=ALkJrhgpCcEnA9GMrwZY4SJoeZuckjkp1Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.transform/javafx.scene.transform.Rotate.html&usg=ALkJrhgpCcEnA9GMrwZY4SJoeZuckjkp1Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2007/09/14/10-minute-tutorial-javafx-event-handling-using-trigger-and-bind/&usg=ALkJrhiiBZs5pZwE-eMc5lCGD-uRVLFy5A
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    17/42

    If you don't know about the bind statement or how JavaFX relates to a scene graph, please reviewmy JavaFX deployment tutorial and JavaFX binding tutorial.

    Step 3: Define the slide show model, part 1

    Now, the actual slide show itself needs a defintion. Since this model class contains most of the

    application logic, I will go over it in sections. First, the variable defintions:noclcik

    class SlideShowModel {def rectangleSlide = SlideModel {x: startX;y: startY;}

    def ellipseSlide = SlideModel {x: nextX;y: nextY;}

    def roundedRectangleSlide = SlideModel {x: nextX;y: nextY;}

    def slides: SlideModel[] = [rectangleSlide, ellipseSlide, roundedRectangleSlide];

    var slideIndex: Number = 0;var slideAnimationRunning: Boolean = false;...}

    The slide show contains three slides each represented by their own SlideModel variable. The classalso holds those three slides in a sequence named slides By indexing into the slides sequence

    , the slideIndex variable represents the currently displaying slide. Finally, the slideAnimationRunning variable simply represents whether or no t slides arecurrentlysliding.

    Step 4: Define the slide show model, part 2

    With the variables out of the way, the functions come next:

    class SlideShowModel {...function isAnimating() {return slideAnimationRunning;}

    function getSlide( newSlideIndex:Integer ): SlideModel {

    if( (newSlideIndex >= sizeof (slides)) or (newSlideIndex < 0) ) {return null ;} else {return slides[newSlideIndex];}}

    function getPrevSlide (): SlideModel {return getSlide( slideIndex - 1 );}

    http://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.transform/javafx.scene.transform.Rotate.html&usg=ALkJrhgpCcEnA9GMrwZY4SJoeZuckjkp1Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.transform/javafx.scene.transform.Rotate.html&usg=ALkJrhgpCcEnA9GMrwZY4SJoeZuckjkp1Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.transform/javafx.scene.transform.Rotate.html&usg=ALkJrhgpCcEnA9GMrwZY4SJoeZuckjkp1Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.transform/javafx.scene.transform.Rotate.html&usg=ALkJrhgpCcEnA9GMrwZY4SJoeZuckjkp1Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2007/09/14/10-minute-tutorial-javafx-event-handling-using-trigger-and-bind/&usg=ALkJrhiiBZs5pZwE-eMc5lCGD-uRVLFy5Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2007/09/14/10-minute-tutorial-javafx-event-handling-using-trigger-and-bind/&usg=ALkJrhiiBZs5pZwE-eMc5lCGD-uRVLFy5Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2A
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    18/42

    function getCurrentSlide (): SlideModel {return getSlide( slideIndex );}

    function getNextSlide (): SlideModel {return getSlide( slideIndex + 1 );}...}

    These functions resemble read-only properties, rather than application logic functions, so theyshouldn't cause any comprehension problems. I highlighted the return null; statement merelyto show that if the caller tries to use an out of bounds slide index, the getSlide function returnsnull. I also highlighted the names of the last three functions to point out that this class allowsnamed access to the previous, current and next slide.

    Step 5: Define the slide show model, part 3

    Finally, the application logic. I'll go through this a function at a time:

    class SlideShowModel {...function rotate() {if( isAnimating() ) {return;}

    var slideRotationAnimation = Timeline {keyFrames: [KeyFrame {time: 0svalues: getCurrentSlide().rotation => 0action: function(): Void {slideAnimationRunning = true;}}

    KeyFrame {time: 3svalues: getCurrentSlide().rotation => 720 tween Interpolator.EASEOUTaction: function(): Void {slideAnimationRunning = false;}}]}

    slideRotationAnimation.playFromStart();}...}

    The rotate function, obviously, rotates a slide. First, it makes sure all other animations havestopped. Then, it creates a javafx.animation.Timeline object, held in slideRotationAnimation,that defines the rotation (I will discuss this class in a moment). And finally, by calling the

    playFromStart function, cu rrent slide rotates.The Timeline class represents an animation time line. You can think of animation as a bunch of pictures, or frames, displayed in rapid succession such that your eye creates smoothmovement. Typically, an animator won't draw each of these frames, they just define a beginningframe and an end frame then let the computer figure out all the frames in between. Animatorscall the beginning and end frames key frames and call the computational process the computer

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    19/42

    goes through to figure ou t the frames in between tweening. During the tweening process,animators can provide the computer with certain rules that define how it should create theframes in between. For example, the animator may want a square to move across the screenfast, but slow down as it gets to the end. So, the animator would tell the computertointerpolate bigger values at the beginning (to move it faster), and then smaller values at theend (to simulate it slowing down).

    Learn more about animationWith those concepts in mind, let's take another look at the

    slideRotationAnimation Timeline object. It defines two key frames on the time line, one at zeroseconds the other at three seconds, meaning the animation will take three seconds tocomplete. The first frame initializes the rotation of the current slide to 0 and through thefunction stored in the action variable, sets slideAnimationRunning to true, so the slide showcan track the running animation. The real magic happens in the definition of the lastframe. Within the three seconds defined in its time variable, it increments the rotation variable of the current slide from zero (as defined in the first frame) to 720 (meaning, it rotatesthe square twice). Note that it uses an EASEOUT interpolation, meaning the rotation will slowdown at the end. And finally, after the last frame completes, the function in t he action variablegets called, telling the slide show that the animation has completed. To start the animation, we

    call its playFromStart() function, which returns immediately since animation happensasynchronously on another thread.The Timeline class contains a running variable, allowing you to check the running state of ananimation. In this particular case, the variable slideRotationAnimation goes out of scope, so I usethe slideAnimationRunning variable to track the running state instead . Note that even thoughthe Timeline object goes out of scope at the end of this function, the animation still runs.

    The documentation for the KeyFrame class , says that the values variable contains a sequenceof KeyValue instances. So, you may wonder exactly how the => and tween syntax translatesinto an instantiation of a KeyValue object. I do too. I couldn't find any good documentation onthis, so I would appreciate any information that could shed light on it.Also, the documentation says that the functions defined in KeyFrame action variables occurAFTER the frame update. So, in this example, there exists a small chance two animations couldoverlap because the slideAnimationRunning variable wouldn't get set until after the first frameoccured. I left this issue in here to see if I could make it happen on my workstation and I onlygot it to happen once.

    Learn more about the Timeline class Learn more about the KeyFrame class Learn more about the Interpolator class

    The rest of the functions follow the same pattern, so they won't pose much of a problem. First,the slideNext function:

    ...function slideNext() {if( ( slideShowModel.getNextSlide() == null) or isAnimating() ) {

    return;}

    var slideNextAnimation = Timeline {keyFrames: [KeyFrame {time: 0svalues: [getCurrentSlide().x => startX,getNextSlide().x => nextX]action: function(): Void {slideAnimationRunning = true;

    http://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://en.wikipedia.org/wiki/Interpolate&usg=ALkJrhj8N4fozQo8yU15A7nJH6lNPLzQ3ghttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://en.wikipedia.org/wiki/Animation&usg=ALkJrhjLw1uyo54BQZNV3f3axsNJbjMI6Qhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.animation/javafx.animation.KeyFrame.html&usg=ALkJrhhaIMkLKtKUxCQO0X3dtMCdYLEvvAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.animation/javafx.animation.KeyFrame.html&usg=ALkJrhhaIMkLKtKUxCQO0X3dtMCdYLEvvAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.animation/javafx.animation.KeyFrame.html&usg=ALkJrhhaIMkLKtKUxCQO0X3dtMCdYLEvvAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.animation/javafx.animation.Timeline.html&usg=ALkJrhhcaUhIgu8tIaL_FvTV9Zy9ADDHhAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.animation/javafx.animation.KeyFrame.html&usg=ALkJrhhaIMkLKtKUxCQO0X3dtMCdYLEvvAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.animation/javafx.animation.Interpolator.html&usg=ALkJrhia9xPQ5OqM2E1yeNmiwK82enrnrwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.animation/javafx.animation.Interpolator.html&usg=ALkJrhia9xPQ5OqM2E1yeNmiwK82enrnrwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.animation/javafx.animation.KeyFrame.html&usg=ALkJrhhaIMkLKtKUxCQO0X3dtMCdYLEvvAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.animation/javafx.animation.Timeline.html&usg=ALkJrhhcaUhIgu8tIaL_FvTV9Zy9ADDHhAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.animation/javafx.animation.KeyFrame.html&usg=ALkJrhhaIMkLKtKUxCQO0X3dtMCdYLEvvAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://en.wikipedia.org/wiki/Animation&usg=ALkJrhjLw1uyo54BQZNV3f3axsNJbjMI6Qhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://en.wikipedia.org/wiki/Interpolate&usg=ALkJrhj8N4fozQo8yU15A7nJH6lNPLzQ3g
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    20/42

    }}KeyFrame {time: 1svalues: [getCurrentSlide().x => (-1 - slideWidth) tween Interpolator.EASEIN,getNextSlide().x => startX tween Interpolator.EASEIN]action: function(): Void {slideAnimationRunning = false;}}]}

    slideNextAnimation.playFromStart();slideIndex++;}...

    I highlighted the important parts. First, like the rotation function, it insures all other animationshave stopped. Additionally, if it has reached the end of the slide show, it also returns. Since boththe slide going out and the slide coming in need animating, the values variable in

    each KeyFrame contains two associations. Note, that the KeyFrame s animate the x coordinate, now.Finally, the slideIndex variable gets incremented, since the slide show hasmoved to the next slide.Updating slideIndex after the asynchronous playFromStart function won't cause any problemsbecause the KeyFrame works from the slide it got initialized with.

    As you can imagine, the slidePrevious function works the same as slideNext:

    ...function slidePrevious() {if( (slideShowModel.getPrevSlide() == null) or isAnimating() ) {return;}

    var slidePrevAnimation = Timeline {keyFrames: [KeyFrame {time: 0svalues: [getCurrentSlide().x => startX,getPrevSlide().x => (-1 - slideWidth)]action: function(): Void {slideAnimationRunning = true;}}KeyFrame {time: 1svalues: [getCurrentSlide().x => width + 1 tween Interpolator.EASEIN,getPrevSlide().x => startX tween Interpolator.EASEIN]

    action: function(): Void {slideAnimationRunning = false;}}]}

    slidePrevAnimation.playFromStart();slideIndex--;}}

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    21/42

    I won't bore you by walking through this code, too. Just extrapolate from slideNext. Now, let's quickly instantiate an instance of the SlideShowModel class:

    var slideShowModel = SlideShowModel {

    }

    Hey, I said quick. All the class initialization happens in the class declaration, so this objectliteral assignment can remain empty.

    Step 6: Define the view model

    Following something akin to the Model-View-ViewModel paradigm, let's create ViewModel classthat bridges elements of the view to the model:

    class ViewModel {def rectangle = Rectangle {width: 40height: 40fill: Color.GREENstroke: Color.BLACK

    x: bind slideShowModel.rectangleSlide.x;y: bind slideShowModel.rectangleSlide.y;transforms: [slideShowModel.rectangleSlide.rotateTransform];}

    def ellipse = Ellipse {radiusX: 20radiusY: 13fill: Color.BLUEstroke: Color.BLACK centerX: bind slideShowModel.ellipseSlide.x + (slideWidth / 2);centerY: bind slideShowModel.ellipseSlide.y + (slideHeight / 2);transforms: [slideShowModel.ellipseSlide.rotateTransform];}

    def roundedRectange = Rectangle {width: 40height: 40arcHeight: 10arcWidth: 10fill: Color.ORANGEstroke: Color.BLACK x: bind slideShowModel.roundedRectangleSlide.x;y: bind slideShowModel.roundedRectangleSlide.y;transforms: [slideShowModel.roundedRectangleSlide.rotateTransform];}

    def shapes: Node[] = [rectangle,ellipse,roundedRectange];}

    Nothing too difficult to understand here, but I want to draw your attention to the highlightedlines. The first line assigns transforms performed on the Rectangle to the transforms inside of athe rectangleSlide SlideModel instance. Without this assignment, rotations wouldn't display. Itappears that whenever JavaFX sees an update to a transform stored in the transforms variableof a class derived from Node it updates that node on the screen. Also, remember that

    rectangeSlide binds the angle property of i ts rotateTransform variable to the rotation

    http://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx&usg=ALkJrhjmMwNTTB0EUemXRvdHT6s_qXEKWwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene/javafx.scene.Node.html&usg=ALkJrhgX7m4AixL2OIgaRMbDgMdCVswtvQhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene/javafx.scene.Node.html&usg=ALkJrhgX7m4AixL2OIgaRMbDgMdCVswtvQhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene/javafx.scene.Node.html&usg=ALkJrhgX7m4AixL2OIgaRMbDgMdCVswtvQhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene/javafx.scene.Node.html&usg=ALkJrhgX7m4AixL2OIgaRMbDgMdCVswtvQhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx&usg=ALkJrhjmMwNTTB0EUemXRvdHT6s_qXEKWw
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    22/42

    property, which gets animated in SlideShowModel.rotate . This effortless flow of data from modelto view displays the true power of JavaFX's declartive data binding.I also highlighted the binding of the Ellipse s position, simply to show that it needs an offsetbecause developers have to position it by its center rather than upper-left coordinate like therectangles.Let's instantiate this model, too:

    var viewModel = ViewModel {

    }

    Step 7: Define the view

    Last but not least, let's create the Stage :

    Stage {title: "Die, Ajax! - Slide Show Sample"width: 300height: 300visible: truescene: Scene {

    content: [viewModel.shapes ,HBox {content: [SwingButton {text: ""action: function(): Void {slideShowModel.slidePrevious();}}]

    translateX: 83translateY: 180}]}}

    After going through my other tutorials, this shouldn't cause you any problems.I highlighted theline where shapes get added for display. I also highlighted where SlideShowModel functions getcalled.

    Learn more about the SwingButton class Learn more about the HBox class

    http://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.ext.swing/javafx.ext.swing.SwingButton.html&usg=ALkJrhj0ynkm_EIoeHR6MUrCinxO5-jmKQhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.layout/javafx.scene.layout.HBox.html&usg=ALkJrhjVAitsdy2M7giH4vlGiF8Oqv686Qhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.layout/javafx.scene.layout.HBox.html&usg=ALkJrhjVAitsdy2M7giH4vlGiF8Oqv686Qhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.ext.swing/javafx.ext.swing.SwingButton.html&usg=ALkJrhj0ynkm_EIoeHR6MUrCinxO5-jmKQ
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    23/42

    Step 8: Run it!

    Without an IDE, building JavaFX applications for the desktop, browser and Webstart remains aslightly involved process. I explain this process step-by-step in my 10 Minute Tutorial - JavaFX:Hello World and 10 Minute JavaFX Tutorial - Develop and deploy JavaFX Applets and Applicationswhile online and offline articles, so I will just walk you through the basics here. Feel free toreference those articles for more detail.

    Compile the code No matter the deployment platform, we need to compile the code first. This line takes care of it:

    "C:\Program Files\JavaFX\javafx-sdk1.0\bin\javafxc.exe" -d . ShapeSlideShow.fx

    Now, we'll look at each platform individually.

    Run the application on the desktop We only need one command to do this:

    "C:\Program Files\JavaFX\javafx-sdk1.0\bin\javafx.exe" com.dieajax.sample.slideShow.ShapeSlideShow

    Run the application as an applet Per my 10 Minute JavaFX Tutorial - Develop and deploy JavaFX Applets and Applications whileonline and offline article, first let's make a JAR file:

    "C:\Program Files\Java\jdk1.6.0_11\bin\jar.exe" cvf ShapeSlideShow.jar com\dieajax\sample\slideshow\ShapeSlideShow*.class

    Can't make it appear in the browser without some HTML, so let's create an HTML file named shapeslideshow -applet.html and add that next:

    Shape Slide Show Applet

    javafx({archive: "ShapeSlideShow.jar",draggable: true,width: 300,height: 300,code: "com.dieajax.sample.slideshow.ShapeSlideShow",name: "ShapeSlideShow"});

    Finally, we need the applet JNLP file named ShapeSlideShow_browser.jnlp:

    Shape Slide Show SampleAcme CorporationShape Slide Show Sample Applet

    http://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.layout/javafx.scene.layout.HBox.html&usg=ALkJrhjVAitsdy2M7giH4vlGiF8Oqv686Qhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.layout/javafx.scene.layout.HBox.html&usg=ALkJrhjVAitsdy2M7giH4vlGiF8Oqv686Qhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://java.sun.com/javafx/1/docs/api/javafx.scene.layout/javafx.scene.layout.HBox.html&usg=ALkJrhjVAitsdy2M7giH4vlGiF8Oqv686Qhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2007/08/23/10-minute-tutorial-javafx-hello-world/&usg=ALkJrhgEoqpgcapwRteK0YCKP9QIZjXqMAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2007/08/23/10-minute-tutorial-javafx-hello-world/&usg=ALkJrhgEoqpgcapwRteK0YCKP9QIZjXqMAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2008/12/19/10-minute-javafx-tutorial-deploy-javafx-applets-and-applications-both-online-and-offline/&usg=ALkJrhjWhJQ3fceBXfbQMmDsqTwDf3Em2Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2007/08/23/10-minute-tutorial-javafx-hello-world/&usg=ALkJrhgEoqpgcapwRteK0YCKP9QIZjXqMAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://www.dieajax.com/2007/08/23/10-minute-tutorial-javafx-hello-world/&usg=ALkJrhgEoqpgcapwRteK0YCKP9QIZjXqMA
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    24/42

    Test this by opening the shapeslideshow -applet.html file in your browser.

    Run the application through Java Webstart Deploying applications through Java Webstart requires HTML, too, so put this code inside of anew file named shapeslideshow -webstart.html:

    Shape Slide Show Webstart

    Shape Slide Show Webstart

    Our Webstart JNLP file, stored in ShapeSlideShow.jnlp will look very similar to the appletversion, but with a few tweaks:

    Shape Slide Show SampleAcme CorporationShape Slide Show Sample Applet

    Remember to change the codebase attribute to match your disk or web serverdirectory structure.To run the application through Java Webstart you should only need to open the

    shapeslideshow -webstart.html file and click on the link.

    Conclusion

    Here is the original Clear button event handler, which simply removes all of thePath nodes in Group lineGroup .

    1

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    25/42

    2

    3

    4

    5

    6

    7

    8

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    26/42

    FadeTransition for each Path node. A FadeTransition animates anode's opacityProperty . To fade out a node (have it disappear), setFadeTransition's toValue to 0.0. To fade in a node (make it appear), set toValue to1.0. If you don't provide a value for fromValue , FadeTransition uses the

    node opacityProperty 's current value.So let's see how our new Clear button event handler works with Transitions. First,if the drawing canvas is empty, we don't do anything and just return. If thesequential transition ( seqtran ) isn't null, then we'll stop it. We instantiate a new SequentialTransition and go through the collection of nodes in Group lineGroup toconstruct a FadeTransition for each node. We specify its duration to be 1,000milliseconds, set toValue to 0 (making the node fade out), andset interpolator to Interpolator.EASE_BOTH . The default interpolator is LINEAR ,providing a constant rate of change for the animation. EASE_IN provides a slowerrate of change at the onset of animation, whereas EASE_OUTis a slower rate of changeat the end. EASE_BOTHprovides slowing at both ends of the animation. After configuring the FadeTransition, we add it to the beginning of theSequentialTransition's collection of animations, providing the reverse ordering. When everything is configured, we initiate the sequential animation withmethod playFromStart() .1

    2

    3

    4

    5

    6

    7

    8

    9

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    27/42

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    (seqtran != null) {

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    28/42

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    29/42

    13

    14

    15

    16

    17

    18

    19

    (); timeline = new Timeline();

    lineGroup.getChildren ()); lineGroup.getChildren());

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    30/42

    Figure 1: Table of JavaFX Transition Classes OverviewTo help you learn how to use the TranslateTransition class, an example named TransitionExampleX will beemployed.As shown in Figure 2, this example contains a couple of buttons, a couple of rectangles, and a circlethat you'll animate a little later.The TransitionExample project that you'll download in the next section contains starter code for this example,and it has an appearance at runtime similar to Figure 2.During the course of this article, you'll modify the codeto implement the animated behavior of the TransitionExampleX project, which is also available to download.

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    31/42

    Figure 2: Screen Capture of the TransitionExampleXExample Program When you click the Play button, the text on the button changes to Pause , as shown in Figure 3, and the ball

    moves back and forth between the paddles indefinitely.

    Figure 3: Screen Capture of the TransitionExampleX After Clicking the Play Button Clicking the Pause button causes the animation to pause and the text on the button to change to Play .Obtaining and Running the TransitionExample Example

    1. Download the NetBeans project (zip file) that includes the TransitionExample program

    2. Expand the project into a directory of your choice.

    3. Start NetBeans, and select the File -> Open Project menu.4. From the Open Project dialog box, navigate to your chosen directory and open

    the TransitionExample project, as shown in Figure 4. If you receive a message dialog stating thatthe jfxrt.jar file can't be found, click the Resolve button and navigate to the rt/lib folder subordinate towhere you installed the JavaFX 2.0 SDK.

    Note : You can obtain the NetBeans IDE from the NetBeans site.

    http://www.oracle.com/technetwork/articles/java/jfxannimation-433998.ziphttp://netbeans.org/http://netbeans.org/http://www.oracle.com/technetwork/articles/java/jfxannimation-433998.zip
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    32/42

    Figure 4: Opening the TransitionExampleProject in NetBeans 1. To run the application, click the Run Project icon on the toolbar, or press the F6 key.The Run Project icon has

    the appearance of the Play button on a DVD player, as shown in Figure 5.

    Figure 5: Invoking the TransitionExample Program in NetBeans

    The TransitionExample application should appear in a window, as shown in Figure 6.

    Figure 6: Screen Capture of the TransitionExampleProgram

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    33/42

    You'll notice that clicking the Play and Stop buttons has no effect.Your mission will be to add code thatimplements the behavior described previously.Here are steps you can follow to implement this behavior:

    Step 1: Create a TranslateTransition Instance to Animate the NodeTo cause the ball to move (also known as translate ) between two different positions in the scene, we'll createan instance of the TranslateTransition class. Take a look at the code in Listing 1, which shows the starter

    code for this example and is located in the TransitionExampleMain.java file.Listing 1: TransitionExampleMain.java

    package transitionexample.ui;

    import javafx.animation.Animation;import javafx.animation.Interpolator;import javafx.animation.TranslateTransition;import javafx.application.Application;import javafx.beans.property.StringProperty;import javafx.builders.ButtonBuilder;import javafx.builders.CircleBuilder;import javafx.builders.GroupBuilder;import javafx.builders.RectangleBuilder;import javafx.builders.SceneBuilder;

    import javafx.builders.TranslateTransitionBuilder;import javafx.builders.VBoxBuilder;import javafx.event.EventHandler;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.VBox;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.stage.Stage;import javafx.util.Duration;

    public class TransitionExampleMain extends Application {

    /*** A reference to the program's Scene*/

    Scene scene;

    /*** A VBox that contains the control buttons*/

    VBox buttonsContainer;

    /*** A TranslateTransition that will animate the ball*/

    TranslateTransition transition;

    /*** The play/pause button*/

    Button playButton;

    /**

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    34/42

    * The Stop button*/

    Button stopButton;

    /*** Strings that hold possible values for text on the Play button*/

    String playText = "Play";String pauseText = "Pause";

    /*** The StringProperty to which the text for the Play button will be bound*/

    StringProperty playButtonText = new StringProperty(playText);

    /*** Invoked as a result of being launched by the Application.launch() call* in the main method below.* @param stage*/

    @Override

    public void start(Stage stage) {

    /*** The ball, whose coordinates will be changed by the TranslateTransition*/

    Circle ball = CircleBuilder.create().radius(10).centerX(30).centerY(130).fill(Color.WHITE).stroke(Color.BLACK).strokeWidth(2)

    .build();

    // Over a duration of 1500 milliseconds, the translateX variable of// the ball node is increased from 0 to 440. At the end of the animation,// the transition reverses back to its starting position (autoReverse is// set to "true"). The cycleCount property specifies how many times to// repeat the transition at the end of the animation. Here, it is set to// Transition.INDEFINITE, meaning it will not stop repeating until the// pause() or stop() methods are called, or the application is closed.

    transition = TranslateTransitionBuilder.create().duration(new Duration(1500.0)).node(ball)

    // TO DO: Insert code to set the fromX property to 0// TO DO: Insert code to set the toX property to 440

    .interpolator(Interpolator.LINEAR)

    // TO DO: Insert code to set the autoReverse property to true

    .cycleCount(Animation.INDEFINITE).build();

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    35/42

    playButton = new ButtonBuilder.create().onAction(new EventHandler() {

    @Override public void handle(javafx.event.ActionEvent e) {if (transition.getStatus() == Animation.Status.PAUSED) {

    // TO DO: Insert code here to start the animation// TO DO: Insert code here to change Play button text to

    pauseText

    }

    else {

    // TO DO: Insert code here to pause the animation// TO DO: Insert code here to change Play button text to

    playText

    }}

    })

    .build();

    stopButton = new ButtonBuilder.create().text("Stop").onAction(new EventHandler() {

    @Override public void handle(javafx.event.ActionEvent e) {

    // TO DO: Insert code here to stop the animation// TO DO: Insert code here to change Play button text to

    playText}

    }})

    .build();

    Scene scene = new SceneBuilder.create().width(500).height(250).root(new GroupBuilder.create()

    .children(new RectangleBuilder.create()

    .x(10)

    .y(120)

    .width(10).height(20)

    .fill(Color.GRAY)

    .stroke(Color.BLACK).build(),

    new RectangleBuilder().x(480).y(120).width(10)

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    36/42

    .height(20)

    .fill(Color.GRAY)

    .stroke(Color.BLACK).build(),ball,

    buttonsContainer = new VBoxBuilder.create().layoutX(100).layoutY(15).alignment(Pos.CENTER).spacing(5).children(

    playButton,stopButton

    ).build()

    ).build())

    .build();

    stage.setScene(scene);stage.setVisible(true);

    // Bind the Play button text to a StringProperty variableplayButton.textProperty().bind(playButtonText);

    // Center the horizontal location of the buttons container in thescene

    // Note: This is to demonstrate binding expressions. Layoutcontainers

    // would normally be the preferred approach.

    buttonsContainer.layoutXProperty().bind(scene.widthProperty().subtract(buttonsContainer.widthProperty()).divide(2.0));

    }

    /*** The main method for this Java application* @param args the command line arguments*/

    public static void main(String[] args) {Application.launch(TransitionExampleMain.class, args);

    }}

    Using the TranslateTransitionBuilder Class to Build TranslateTransitionThe starter code shown in Listing 1 makes use of builder classes in the javafx.builders package of theJavaFX 2.0 API, including the TranslateTransitionBuilder class shown here:transition = new TranslateTransitionBuilder.create()

    .duration(new Duration(1500.0))

    .node(ball)

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    37/42

    // TO DO: Insert code to set the fromX property to 0// TO DO: Insert code to set the toX property to 440.interpolator(Interpolator.LINEAR)// TO DO: Insert code to set the autoReverse property to true.cycleCount(Animation.INDEFINITE)

    .build();

    Go ahead and fill in the lines indicated by the TO DO comments, so the code block shown above turns intothe one shown below:

    transition = new TranslateTransitionBuilder().duration(new Duration(1500.0)).node(ball).fromX(0).toX(440).interpolator(Interpolator.LINEAR).autoReverse(true).cycleCount(Animation.INDEFINITE).build();

    There are many builder classes in the JavaFX API, and their purpose is to enable a declarative-style ofprogramming to create and set the properties of objects.For example, the code that you filled in above createsan instance of the TranslateTransition class, and it populates that instance with properties such as theduration of the animation and the node in the scene graph being animated.As you can see in Listing 1, otherbuilder classes used in this applicationinclude ButtonBuilder , CircleBuilder , RectangleBuilder , SceneBuilder and VBoxBuilder .

    Step 2: Define an Event Handler in the Play ButtonTo make the TranslateTransition start, pause, and stop, you'll define event handlers in the buttons that callthe appropriate methods on the TranslateTransition object.For example, the starter code below from Listing 1contains the builder that creates a Button instance for the Play button.playButton = new ButtonBuilder.create()

    .onAction(new EventHandler() {@Override public void handle(javafx.event.ActionEvent e) {if (transition.getStatus() == Animation.Status.PAUSED) {

    // TO DO: Insert code here to play the animation// TO DO: Insert code here to change Play button text to pauseText

    }else {

    // TO DO: Insert code here to pause the animation// TO DO: Insert code here to change Play button text to playText

    }}

    }).build();

    As you did before, fill in the lines indicated by the TO DO" comments, turning the code block shown above intothe one shown below:

    playButton = new ButtonBuilder.create().onAction(new EventHandler() {

    @Override public void handle(javafx.event.ActionEvent e) {if (transition.getStatus() == Animation.Status.PAUSED) {

    transition.play();playButtonText.setValue(pauseText);

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    38/42

    }else {

    transition.pause();playButtonText.setValue(playText);

    }}

    }).build();

    Using Methods of the Animation Class to Control the AnimationAll the transition classes used in Figure 1 are subclasses of the Transition class, which is a subclass ofthe Animation class.The Animation class has methods such as start() and getStatus() that control andmonitor the state of the animation.As a result of the code that you filled in just now, when the button is clicked,the status of the animation is ascertained.If the animation status is PAUSED , the play( ) method of theanimation is invoked; otherwise, the pause() method is called.Using Binding to Keep Properties UpdatedProperty binding is a very convenient and powerful feature of the JavaFX API, because it enables you to keepthe values of properties automatically updated.The following excerpts from Listing 1 bind the textProperty ofthe playButton to a StringProperty that holds the text to be displayed in the button:

    String playText = "Play";

    ...StringProperty playButtonText = new StringProperty(playText);

    ...playButton.textProperty().bind(playButtonText);

    As the value of playButtonText is updated by the event handler that you just coded, the text on the buttondisplays the updated value.There is another use of property binding in Listing 1, which is shown in the following excerpt and demonstrateshow to bind expressions:

    buttonsContainer.layoutXProperty().bind(scene.widthProperty().subtract(buttonsContainer.widthProperty()).divide(2.0));

    To keep the buttonsContainer node horizontally centered in the application window, the layoutXProperty of

    one of the nodes in the scene graph is bound to an expression that contains the widthProperty of the Scene .Note :The excerpt above is for demonstration purposes, because the use of layout containers (inthe javafx.scene.layout package) is normally the preferred approach for dynamically positioning nodes withina scene.

    Step 3: Define an Event Handler in the Stop ButtonTo finish the TransitionExample, you'll need to enter some code into the following starter code from Listing 1:

    stopButton = new ButtonBuilder.create().text("Stop").onAction(new EventHandler() {@Override public void handle(javafx.event.ActionEvent e) {

    // TO DO: Insert code here to stop the animation// TO DO: Insert code here to change Play button text to playText}

    }).build();

    The completed code for the Stop button event handler is very similar to what you've already coded in the Playbutton event handler.Go ahead and fill in the code as shown below, and run the example.

    stopButton = new ButtonBuilder.create().text("Stop")

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    39/42

    .onAction(new EventHandler() {@Override public void handle(javafx.event.ActionEvent e) {

    transition.stop();playButtonText.setValue(playText);

    }})

    .build();

    ConclusionJavaFX 2.0 comes with several transition classes (that extend the Transition class whose purpose is toanimate visual nodes in your application.JavaFX also contains many builder classes that provide the ability toexpress a user interface in a declarative style.In addition, JavaFX has a powerful property binding capability inwhich properties may be bound to expressions to automatically keep them updated.See Also

    TIAINEN January 06, 2010

    Simple animation in JavaFX

    Having two weeks off during the Christmas holidays gives you some time to create something in

    JavaFX. I had already used JavaFX before, but animations were a part I didn't yet have anyexperience in. So I was thinking of remaking a simple banner application that a client once

    needed for his website. That version was written in Flash and was created by a third party. You

    can have a look at that animation at http://vi.be .

    The application is quite simple. It reads in an XML-file which contains a list of banners. Eachbanner has an image, a title, a description and a URL. After the XML-file has been read, itdisplays the banners one after another. The transition between two different banners is done byusing a simple fading out/fading in animation. Doing this animation in JavaFX is simple.

    http://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/&usg=ALkJrhggn37YFqRdBULLzJRty12924qsXQhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/2010/01/simple-animation-in-javafx.html&usg=ALkJrhhl8RqEt70hGahD6kyao2VTya5upAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://vi.be/&usg=ALkJrhgSI4bb3LKCbqfODaT74QStFCSMkwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://vi.be/&usg=ALkJrhgSI4bb3LKCbqfODaT74QStFCSMkwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://vi.be/&usg=ALkJrhgSI4bb3LKCbqfODaT74QStFCSMkwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://vi.be/&usg=ALkJrhgSI4bb3LKCbqfODaT74QStFCSMkwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/2010/01/simple-animation-in-javafx.html&usg=ALkJrhhl8RqEt70hGahD6kyao2VTya5upAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/&usg=ALkJrhggn37YFqRdBULLzJRty12924qsXQ
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    40/42

    First I create a variable to hold the current opacity and bind this to the opacity of the

    banner. The SingleBanner class used below is nothing more than a CustomNode in which theimage, the title and the description are placed.

    var bannerOpacity = 1.0;

    insert SingleBanner {

    banner : banner // the POJO containing all banner info

    visible : false // initially all banners are invisible

    opacity : bind bannerOpacity // bind the opacity variable to the banner

    // when the mouse is hovering over the banner, pause the timeline

    onMouseEntered : function(event : MouseEvent) {timeline.pause();

    }

    onMouseExited : function(event : MouseEvent) {

    timeline.play();

    }

    } into banners;

    To do the actual animation in JavaFX, we need to create a Timeline. A Timeline does nothingmore than perform actions at specified "keyframes". You can execute this Timeline once, a fewtimes or even infinitely. Here's the code for our Timeline:

    var timeline : Timeline = Timeline {

    repeatCount : Timeline.INDEFINITE

    keyFrames: [

    at (4.75s) {

    bannerOpacity => 1.0},

    at (4.85s) {

    bannerOpacity => 0.0 tween Interpolator.EASEOUT

    }

    at (5.0s) {

    bannerOpacity => 1.0 tween Interpolator.EASEIN

  • 8/2/2019 Ejemplo simple de animacin JavaFX

    41/42

    }

    ]

    }

    The syntax is easy to understand and you can clearly see what the Timeline does. 4.75 secondafter the Timeline was started, it will assign 1.0 to the variable bannerOpacity. Between 4.75and 4.85 seconds the opacity will be brought down to zero using an EaseOut

    interpolation. Finally, the opacity will be brought back up to 1.0 with an EaseIninterpolation. The trick is now to make the current banner invisble when the opacity reaches0. At the same time, the next banner in the array will be made visible. We can do that easilyusing a replace trigger.

    var bannerOpacity = 1.0 on replace {

    if (bannerOpacity == 0.0) {

    counters[index].active = false;

    if (index + 1 >= sizeof(banners)) {

    index = 0;

    } else {

    index++;

    }

    counters[index].active = true;}

    }

    var index = 0;

    var banner = bind banners[index] on replace oldBanner {

    oldBanner.visible = false;

    banner.visible = true;

    }

    That's all that is required to do some simple animation. The code for the project canbe downloaded here . There are only two problems that I couldn't resolve:

    http://blog.sertik.net/files/vibebanner/vibebanner.ziphttp://blog.sertik.net/files/vibebanner/vibebanner.ziphttp://blog.sertik.net/files/vibebanner/vibebanner.ziphttp://blog.sertik.net/files/vibebanner/vibebanner.zip
  • 8/2/2019 Ejemplo simple de animacin JavaFX

    42/42

    I have not yet found a way how to open a URL from within JavaFX. This can be achievedwith: AppletStageExtension.showDocument(banner.link, "_new");

    In browser mode the loading of the images takes a long time. In desktop mode it seems togo a lot quicker.

    Below you can have a look at the banner application itself.

    Written by Joeri Sykora on 22:47

    Labels: animation , banner , java , javafx , vibe

    http://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/2010/01/simple-animation-in-javafx.html&usg=ALkJrhhl8RqEt70hGahD6kyao2VTya5upAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/2010/01/simple-animation-in-javafx.html&usg=ALkJrhhl8RqEt70hGahD6kyao2VTya5upAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/2010/01/simple-animation-in-javafx.html&usg=ALkJrhhl8RqEt70hGahD6kyao2VTya5upAhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/animation&usg=ALkJrhjac_HZNuEqQrYB_19mAtbQ79YA2whttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/animation&usg=ALkJrhjac_HZNuEqQrYB_19mAtbQ79YA2whttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/animation&usg=ALkJrhjac_HZNuEqQrYB_19mAtbQ79YA2whttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/banner&usg=ALkJrhhR6AdC4VyKck8E-SAdDI7wIpk4_Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/banner&usg=ALkJrhhR6AdC4VyKck8E-SAdDI7wIpk4_Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/banner&usg=ALkJrhhR6AdC4VyKck8E-SAdDI7wIpk4_Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/java&usg=ALkJrhi7GxjjLcrTcVakdLXqat1sJhAsmwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/java&usg=ALkJrhi7GxjjLcrTcVakdLXqat1sJhAsmwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/java&usg=ALkJrhi7GxjjLcrTcVakdLXqat1sJhAsmwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/javafx&usg=ALkJrhgq1iAev7TFxT1PC17iPai9jWQFsghttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/javafx&usg=ALkJrhgq1iAev7TFxT1PC17iPai9jWQFsghttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/javafx&usg=ALkJrhgq1iAev7TFxT1PC17iPai9jWQFsghttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/vibe&usg=ALkJrhiyrsHsEd36uno2SVQWuSZgTV0T6ghttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/vibe&usg=ALkJrhiyrsHsEd36uno2SVQWuSZgTV0T6ghttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/vibe&usg=ALkJrhiyrsHsEd36uno2SVQWuSZgTV0T6ghttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/vibe&usg=ALkJrhiyrsHsEd36uno2SVQWuSZgTV0T6ghttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/javafx&usg=ALkJrhgq1iAev7TFxT1PC17iPai9jWQFsghttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/java&usg=ALkJrhi7GxjjLcrTcVakdLXqat1sJhAsmwhttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/banner&usg=ALkJrhhR6AdC4VyKck8E-SAdDI7wIpk4_Ahttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/search/label/animation&usg=ALkJrhjac_HZNuEqQrYB_19mAtbQ79YA2whttp://translate.googleusercontent.com/translate_c?anno=2&hl=es&rurl=translate.google.com.mx&sl=en&tl=es&twu=1&u=http://tiainen.sertik.net/2010/01/simple-animation-in-javafx.html&usg=ALkJrhhl8RqEt70hGahD6kyao2VTya5upA