JavaFX

Tecnología Java |29 de octubre de 2011

  • Es una nueva familia de productos basados en la tecnología Java™
  • Presentado por Sun en Mayo del 2007 y lanzada oficialmente la versión 1.0 en Diciembre del 2008
  • Pensado para competir con Adobe Flex y Microsoft Silverlight en la arena de las Rich Internet Applications
  • JavaFX Script y JavaFX Mobile en Febrero del 2009


Qué es JavaFX?
• Plataforma de software pensada para crear y desplegar Aplicaciones Ricas de Internet (RIA), que funciona en una gran variedad de dispositivos
• Integrado en el Java Runtime Environment (JRE)
• Las aplicaciones JavaFX se ejecutarán en cualquier escritorio que tenga instalado el JRE, y además en los dispositivos con soporte Java ME (J2ME)
• En OS de escritorio, la versión actual de JavaFX se soporta -oficialmente- en los sistemas operativos
Windows XP, Vista y Mac OS X *
• En dispositivos móviles, JavaFX es capaz de ejecutarse en múltiples sistemas operativos, incluidos Windows Mobile y Android, además de los propietarios.
* Con un par de ajustes podremos hacer funcionar JavaFX en Linux y OpenSolaris (aún no soportados)

• JavaFX Mobile:
> Sistema de software completo para dispositivos móviles
> Disponible para operadoras, fabricantes de teléfonos, etc.
• JavaFX Script:
> Lenguaje de script orientado a objetos
> Síntaxis simplificada
> Diferente al Java tradicional

• Para crear aplicaciones JavaFX, el desarrollador utiliza un lenguaje de scripting orientado a objetos
llamado JavaFX Script


Componentes que forman JavaFX
• El SDK: compilador, librerías (gráficos, texto, web services, etc.) runtime y todas las herramientas
necesarias para crear y desarrollar aplicaciones
• Production Suite: plugins para Adobe Photoshop e Illustrator que permiten generar código JavaFX a partir de los gráficos generados; conversores de SVG, etc.

Características de JavaFX
Perfil común (Common Profile)
• Existe un concepto de "Perfil común" que intenta unificar todos los dispositivos soportados.

• Ésta técnica permite a los programadores utilizar un modelo de desarrollo común, pudiendo crear una
aplicación orientada a escritorio o a dispositivo móvil, compartiendo gran parte del código fuente, gráficos y contenido entre ambas versiones.

Arrastrar para Instalar (Drag to Install)
• Permite arrastrar un widget o una aplicación JavaFX que reside en una página web (dentro de la ventana del navegador) hacia el escritorio
• La aplicación no perderá su estado o contexto incluso habiendo cerrado el navegador
• Podrá volver a lanzarse a través de un icono que se genera automáticamente en el escritorio
• Ésta característica permite a los desarrolladores “ampliar fronteras” fuera del navegador

Production Suite
• Plugins para Adobe Photoshop e Illustrator que nos permiten crear gráficos avanzados que puedan ser
integrados directamente en aplicaciones JavaFX
• Los plugins generan código JavaFX Script que preserva las capas y la estructura de los gráficos
• Los desarrolladores pueden añadir animaciones fácilmente a los gráficos que importan desde PS o AI
• Herramientas para importar gráficos SVG

 

Getting Started With JavaFX Technology Using NetBeans IDE
This article explains how to get started with the JavaFX technology by using the NetBeans IDE for JavaFX.
In this article, you create an application that displays a docked icon. When you hover the icon with a mouse cursor, it starts bouncing. To stop the icon, point the cursor outside the icon. The application is shown in the following figure.

  1. Ensure that you have the NetBeans IDE 6.9 for JavaFX 1.3 software or later version already installed on your system. If necessary, you can download the latest version from the Downloads page. 
  2. Start the NetBeans IDE. 
  3. Create a JavaFX Script Application project.

    1. Choose File > New Project (Ctrl-Shift-N on Windows).
    2. In the New Project wizard, select JavaFX in the Categories pane and JavaFX Script Application in the Projects pane. Click Next. 
    3. On the Name and Location page, type FirstJavaFXApp for the Project Name, specify your desired location for the project's files in the Project Location text field, and leave all the other default values unchanged, as shown in Figure 1.

Descripción: New Project wizard with project name and location specified.

Figure 1: New Project Wizard With Project Name and Location Specified

    1. Click Finish. 

      The FirstJavaFXApp project opens in both the Projects window and the Files window, and the Main.fxfile opens in the source editor, as shown in Figure 2.

Descripción: FirstJavaFXApp Project Opened in Projects Window and <code>Main.fx</code> File  in the Source Editor.

Figure 2: FirstJavaFXApp Project Opened in Projects Window and Main.fx File in the Source Editor

Notice that JavaFX Script code is included within the Main.fx file by default. This code includes several import statements and object literals such as Stage. These Object literals represent key concepts within the JavaFX application, and are described in the following table.


Table 1: Object Literals Created by Default

Object Literal

Description

Stage

The top level container window required to display any visible JavaFX objects. The default instance variables title, width and height define the text that appears on the window's top border and its height and width. The scene variable defines an instance of the Scene object literal which sets the area in which you can place the JavaFX objects.

Scene

Similar to a drawing surface for the graphical content of your application. The sceneinstance variable has a content variable that is used to hold JavaFX graphical elements and defines the graphical content of your application. The instance variables, width andheight, define the width and height of the content area. For more information about theScene class, see Presenting UI Objects in a Graphical Scene, a lesson in Building GUI Applications With JavaFX.

Text

Defines the graphical element that displays text in the scene.

Font

Defines the font used to display the text in the scene.

  1. In the JavaFX App project, create a folder named resources to store graphical images used in your application.

    1. In the Projects window, right-click the package name and choose New > Folder. If there is no Folder item, choose New > Other and perform additionally step b.

Descripción: The project name firstjavafxapp is right-clicked and item New > File is chosen.

Figure 3: Adding a Folder to Store Graphical Resources

    1. In the New File dialog box, select Other under Categories and Folder under File Types. Click Next.

Descripción: New File dialog with Folder item under File Types selected.

Figure 4: Selecting a Folder in the New File Dialog Box

    1. In the New Folder dialog box, type resources in the Folder Name field and click Finish.
    2. Download the mailIcon.png and dock.jpg files and save them in the resources folder. 
  1. To work with images in JavaFX applications, you use the Image and ImageView classes. The Image class loads the image from the specified location. The ImageView class displays the image in your application. Create a variable to display the dock.jpg image. 

    1. Copy the following lines in bold and paste them into the editor before the code for the Stage object. Notice that an error flag appears. This error is removed in the next step.

Source Code
import javafx.scene.text.Font;

 

def backGround = ImageView {
    image: Image {url: "{__DIR__}resources/dock.jpg"}
    }

Stage {
title: "Application title"
scene: Scene {

    1. Right-click in any white space in the editor and select Fix Imports (Ctrl-Shift-I on Windows) to remove the error flag. You need to select the type of Image by double-clicking thejavafx.scene.image.Image line. 

Descripción: Select the type of Image when fixing imports.

Figure 5: Selecting Image Class When Fixing Imports

    1. Similarly, select the type of ImageView by double-clicking the javafx.scene.image.ImageViewline.

      The following import statements are added to the top of the Main.fx file.

Source Code

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

 

  1. Modify the Stage object as shown in the following example so that the window has a title. Modify the Sceneobject to specify the size of the content area and to replace a text object with the image defined by thebackGround variable. 

    1. Type the new title of your application and specify the values of the width and height variables. Remove the code of the Text object and add the backGround variable to the content of the scene. You can copy the lines in bold and paste them into the editor.

Source Code
Stage {
title: "First JavaFX Application"
    scene: Scene {
        width: 362
        height: 150
        content: [
            backGround
        ]// content
    } // Scene
}// Stage

    1. Notice that warning flags appear, as you have unused imports now. This warning is removed by selecting the Fix Imports (Ctrl-Shift-I on Windows) command.
  1. Declare the icon variable and add it to the scene as shown in the following example. Note the importance of order when adding nodes to the scene. You add the icon node after the backGround node so that the icon is displayed over the background.

Source Code
import javafx.scene.image.ImageView;

 

def icon = ImageView {
    image: Image {url: "{__DIR__}resources/mailIcon.png"}
    }
def backGround = ImageView {
image: Image {url: "{__DIR__}resources/dock.png"}
}

Stage {
title: "First JavaFX Application"
scene: Scene {
width: 362
height: 150
content: [
backGround,
             icon
]//content
}//scene
}//Stage

  1. Save the code (Ctrl-S on Windows) and turn on the Preview feature by clicking the Enable Preview button Descripción: http://download.oracle.com/javafx/1.3/getstarted/im/preview.gifon the editor toolbar.

    A JavaFX Preview window shows the current state of your application, as shown in the following figure. The Preview feature enables you to view the saved state of the GUI design that you are creating. Whenever you want to preview the GUI of your application, save the code first.

Descripción: An icon in the upper left corner of the application

Figure 6: Current State of Application in JavaFX Preview Window

 

By default, a node is displayed at the point (0,0). Now you need to shift the icon so that it looks like a docked icon.

  1. Shift the icon node by translating its coordinates along the X and Y axes as shown in the following example.

Source Code
def icon = ImageView {
image: Image {url: "{__DIR__}resources/mailIcon.png"}
translateX: 133
    translateY: 30
}
}

  1. Define an animated behavior of the icon to move it up and down. The TranslateTransition class ideally fits this purpose, as it creates a move animation that spans the specified duration. 

    1. Drag the Transitions > Translate Transition element from the Palette to the line just after thebackGround variable. When you drag elements from the Palette, the IDE takes care of missing imports for you.

Descripción: Translate Transition element to drag to Source Editor before the Stage object

Figure 7: Drag Translate Transition Element From Palette to Source Editor

    1. Declare a variable named transition that is an instance of the TranslateTransition class applied to the icon node. 

      The rate of the icon's move is controlled by the duration and byY variables. Set the repeatCountvariable to INDEFINITE, as animation will be started and stopped in response to mouse events.

Notice that error flags appear, as some imports now are missing. You remove the errors in the next step.
Source Code

var transition = TranslateTransition {
        duration: 650ms
        node: icon
        byY:- 25
        repeatCount: Timeline.INDEFINITE
        autoReverse: true
    }  

Stage {
title: "First JavaFX Application"

    1. Select the Fix Imports command. For the type of Timeline, select the javafx.animation.Timelineclass.

The following import statement is added to the top of the Main.fx file.
Source Code
import javafx.animation.Timeline;

 

  1. Modify the code of the icon node to start the animation when the icon is hovered with a mouse cursor and pause the animation when the mouse cursor is taken away from the icon. 
    1. Drag the Actions > onMouseEntered element from the Palette to the icon variable initialization to define the onMouseEntered function, which is called when the mouse cursor enters the icon object. 

Descripción: onMouseEntered element to drag from Palette to Source Editor

Figure 8: Drag onMouseEntered Element From Palette to Source Editor

    1. Modify the code of the onMouseEntered function to start the animated transition as shown in the following example.

Source Code
def icon = ImageView {
image: Image {url: "{__DIR__}resources/mailIcon.png"}
translateX: 133
translateY: 30
onMouseEntered: function (e: MouseEvent): Void {
transition.play()
}
}

    1. Notice that an error flag appears in the transition variable code. Hover the error flag with the mouse cursor to learn that you have a cyclic reference to the icon node. The error appeared after you added the onMouseEntered function that references the transition variable. Hover a warning flag to the left of the icon variable initialization line to view an editor hint to declare an explicit type of the icon variable. Modify your code as shown in the following example.

Source Code
var icon: ImageView;
    icon = ImageView {
image: Image {url: "{__DIR__}resources/mailIcon.png"}
translateX: 133
translateY: 30
onMouseEntered: function (e: MouseEvent): Void {
transition.play()
}//onMouseEntered
}

    1. Drag the Actions > onMouseExited element from the Palette to the icon variable initialization after theonMouseEntered function to define the onMouseExited function, which is called when the mouse cursor exits the icon object. 

      Modify the code of the function to pause the animated transition.

Source Code
var icon: ImageView;
icon = ImageView {
image: Image {url: "{__DIR__}resources/mailIcon.png"}
translateX: 133
translateY: 30
onMouseEntered: function (e: MouseEvent): Void {
transition.play()
}//onMouseEntered
onMouseExited: function (e: MouseEvent): Void {
transition.pause()
}//onMouseExited
}

  1. Save the code and run the project.

In the Projects window, right-click the FirstJavaFXApp project node and select Run Project. 

The IDE compiles the project and prepares the files necessary to run the application using the standard execution model. When the project is compiled successfully, an icon is displayed in the center of the application window. 

Investigaciones

Companeros

  • Pamela Alvarado
  • Daniel Garcia
  • Elio Mendoza
  • William Taracena
  • Luis Garcia
  • Derwin Santacruz
  • Hellen Hernandez
  • Manuel Monroy
  • Susana Alvarez
  • Pablo Cruz