Use JavaFX to quickly create applications

JavaFX + Eclipse IDE = Easy GUI

Learn how to develop JavaFX-based Rich Internet Applications using the Eclipse IDE. This article introduces you to JavaFX and explains how to use it in conjunction with the JavaFX Eclipse plug-in to quickly build GUI applications. Explore some of the JavaFX features by building a sample application for both the desktop and a mobile emulator. Also learn to create rudimentary animation.

Ravikumar Vishwakarma (viraviku@in.ibm.com), Software Engineer, IBM

Ravikumar Vishwakarma, a Staff Software Engineer at the IBM India Software Lab in Mumbai, is part of the IBM WebSphere Content Pack Product team. He has been involved with Content Pack for more than three years. He currently uses IBM WebSphere BPM Stack products for developing SOA applications. He is currently involved in creating BPM Solutions using IBM WebSphere Lombardi. Ravikumar has also worked on creating UIs using Lotus Forms Designer. You can reach him at ravikumarv@in.ibm.com.



Rohit Sardesai (rohitsardesai@in.ibm.com), Software Engineer, IBM

Rohit Sardesai photoRohit Sardesai works as a Staff Software Engineer in the IBM India Software Lab and is a part of the Application and Integration Middleware (AIM) team. His key technical skills involve Eclipse plug-in development, OSGI, and Web 2.0 technologies (Dojo and REST). He has published an article series about building dynamic business applications using WebSphere Business Services Fabric (WBSF). He is also actively involved in various Biztech projects. Currently, he is working on BPM Repository and Clustering. You can reach Rohit at rohitsardesai@in.ibm.com.



12 October 2010

Also available in Chinese Japanese

Overview

JavaFX is a Java-based platform for building Rich Internet Applications (RIAs) that can run on a desktop or on mobile devices. Applications built with JavaFX are Java bytecode-based, so they can run on any desktop with the Java runtime environment or on any mobile with Java2 ME installed. JavaFX makes GUI programming very easy; it uses a declarative syntax and provides animation support.

In this article, learn how to get started with JavaFX to build RIAs. Download and install the JavaFX SDK, install the JavaFX Eclipse plug-in, and explore some basic features of JavaFX by creating sample applications.

Download the source code for the Login Application and the Animated Circle examples used in this article.

Installation

Follow these steps to download and install the JavaFX SDK and the JavaFX Eclipse plug-in.

  1. Download the latest JavaFX SDK installer file for Windows, which is an ".exe" extension. After the download is complete, double-click the ".exe" to run the installer.
  2. Complete the steps in the installation wizard.

    The default installation location for Windows is C:\Program Files\JavaFX\javafx-sdk-version.

  3. Start the Eclipse IDE. Provide a workspace name, such as C:/workspace/jfx_projects.
  4. Select Help > Install New Software.
  5. Click Add in the Install dialog that pops up.
  6. As shown in Figure 1, enter JavaFX Plugin Site for the Name, and http://javafx.com/downloads/eclipse-plugin/ for the Location from which the plug-in needs to be installed.
    Figure 1. Add JavaFX Plug-in Site
    Dialog box in which to enter Name and Location

    Click OK.

  7. Check the JavaFX feature that needs to be installed, as shown in Figure 2.
    Figure 2. Check the JavaFX feature to be installed
    Dialog box from which to choose which software features to install

    Click Next.

  8. The JavaFX feature version is displayed in the Install Details dialog. Click Next.
  9. Accept the terms of license agreements and click Finish.
  10. Upon successful installation of the plug-in, restart the Eclipse workbench when prompted.

If you installed the JavaFX SDK in a non-default location, you might be prompted to set the JAVAFX_HOME variable, as shown in Figure 3. You will also need to create a classpath variable called JAVAFX_HOME if it was not created by the Eclipse plug-in installation. Point it to the JavaFX install location.

Figure 3. Setting the JAVAFX_HOME classpath variable
The Classpath Variables dialog prompts you to choose the JavaFX install location

Creating a Login application

In this section, build a sample JavaFX application to validate users against their passwords and allow them to log in to a system if they can provide the required credentials. Upon successful authorization, the user will see a Welcome screen. If authorization is not successful, a message in the Eclipse Console view will provide the failure details. You'll use the JavaFX swing components to build the login screen. You can download the source code for the Login application.

  1. Create a new JavaFX project. Click File > New > Project > JavaFX > JavaFX project, as shown in Figure 4.
    Figure 4. Create a new JavaFX project
    The New Project box prompts you to select a wizard

    Click Next.

  2. Enter LoginApp as the Project name. Select the Desktop profile. These selections are shown in Figure 5.
    Figure 5. Configuring the JavaFX project
    The New JavaFX Project box uses radio buttons to track your selections

    Click Finish.

  3. Create a package called com.sample.login within the LoginApp project.
  4. Right-click the package and select New > Empty JavaFX Script.
  5. Provide the name Main, and then click Finish.
  6. You'll need to declare a few variables for the example application. As shown in Listing 1, you need a Boolean variable called login that maintains the login state of the user (whether or not the last login was successful). Declare the string variable username so that it holds the user name entered by the user. There's also a hard-coded system user test who can only log in to our application.
    Listing 1. Declaration of global variables
    var login = false;
    var userName = "";
    var systemUser = "test";
  7. In the Snippets window, select the Applications tab to expand it.
  8. Select and drag the Stage object to the source editor, as shown in Figure 6. The Stage is the top-level container for holding the user interface JavaFX objects.
    Figure 6. Drag the Stage object onto the editor
    The Stage object is visible on the right
  9. Edit the title to be displayed for the Stage by entering Login App, as shown in Figure 7. Set both the width and the height to 300.
    Figure 7. Configuring the Stage object
    By configuring the height and width values, you determine the size of the Stage

    Click Insert, which will add a Scene element to the Stage. The Scene element is like a drawing platform or surface, which is used to render the graphical elements. It has a content variable that holds the child elements.

  10. Add a javafx.scene.Group element to the Scene with an import statement, as shown in Listing 2. This group will act like a container for the rest of the controls you create.
    Listing 2. Import the group class
    import javafx.scene.Group;
  11. Add the group element, as shown in Listing 3, to the content element.
    Listing 3. Add the group inside the content
    content: [
             Group {
            	    
             }  
    ]
  12. Begin adding child controls to the parent group control. First, add a label by importing the SwingLabel class, as shown in Listing 4.
    Listing 4. Import SwingLabel class
    import javafx.ext.swing.SwingLabel;

    Add the following code to the content element of the group, as shown in Listing 5.
    Listing 5. Add the SwingLabel to the group
    content : [
            	    
              SwingLabel {
                     text : "User Name :";
                    
              }
    ]
  13. Add a Text field control that will accept user input. Import the SwingTextField class, as shown in Listing 6.
    Listing 6. Declaration of variables
    import javafx.ext.swing.SwingTextField;

    Add the highlighted code to add the text field, as shown in Listing 7.
    Listing 7. Add the SwingTextField to the group
    SwingLabel {
              text : "User Name :";
            	       
             },
    SwingTextField {
              text : bind userName with inverse;
              columns : 10;
              editable : true;
              layoutX : 30;
              layoutY : 20;
              borderless : false;
              selectOnFocus : true;
               
                 } 
    
  14. Add a button that will invoke the action to validate the user name entered. If the user name matches the system user, then the user successfully logs in to the system. Import the JavaFX SwingButton using the import statement shown in Listing 8.
    Listing 8. Import the SwingButton class
    import javafx.ext.swing.SwingButton;

    Add the code shown in Listing 9 to include the button just below the Text field.

    Listing 9. Add the SwingButton to the group
     SwingButton{
             translateX: 50
             translateY: 50
             text: "Submit"
             action: function(){
              if((userName != systemUser)) {
                  println("Invalid UserName");
              }
              login = (userName == systemUser);
             }
            }
  15. The action function in Listing 9 checks if the userName that was entered is the same as the system user name. If it is not, the example prints out the error message. Otherwise, the result is stored in the login Boolean variable.

    So far you've handled the case where the login fails. You need to use the state of the login variable to advance to the successful login screen. This demands an if-else statement. Add the if-else clause, and in the else clause, first add an empty group with a content object in it. Add the highlighted code, as shown in Listing 10.

    Listing 10. Add the if-else clause
                            content: bind if(not login)Group {
                            content: [
                            SwingLabel{
                            text: "User Name:"
                            },
                            SwingTextField {
                            text : bind userName with inverse;
                            columns : 10;
                            editable : true;
                            layoutX : 30;
                            layoutY : 20;
                    },
                    SwingButton{
                          translateX: 50
                          translateY: 50
                          text: "Submit"
                          action: function(){
                                if((userName != systemUser)) {
                                      println("Invalid UserName");
                                }
                                login = (userName == systemUser);
                          }
                    }
                  ]
                 } 
                  else Group{
                             content: [
                  
                       	  ]
            
                  }
  16. Finally, add some text to indicate a successful login message and a Log out button that will return the user to the login screen. Import the Text class, as shown in Listing 11.
    Listing 11. Import the Text class
     import javafx.scene.text.Text;

    Add the code shown in Listing 12 inside the content body of the else clause group element you added earlier.
    Listing 12. Add the Text Class and SwingButton to the else group
    Text {
           x: 10 y: 30
           content: "You have successfully logged in."
          },
    SwingButton{
         translateX: 10
         translateY: 50
         text: "Log out"
         action: function(){
     	userName = "";
     	login = false;
         }
     }

The complete code is shown in Listing 13.

Listing 13. LoginApp example code
package com.sample.login;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.text.Text;

import javafx.ext.swing.SwingLabel;
import javafx.ext.swing.SwingTextField;
import javafx.ext.swing.SwingButton;

var login = false;
var userName = "";
var systemUser = "test";
Stage {
    title : "Login App"
    scene: Scene {
        width: 300
        height: 300
        content: bind if(not login) Group{
                          content: [
                             SwingLabel{
                                 text: "User Name:"
                             },
                             
                             SwingTextField {
                                 text : bind userName with inverse;
                                 columns : 10;
                                 editable : true;
                                 layoutX : 30;
                                 layoutY : 20;
                                  
                             },
                             SwingButton{
                                 translateX: 50
                                 translateY: 50
                                 text: "Submit"
                                 action: function(){
                                     if((userName != systemUser)) {
                                            println("Invalid UserName");
                                           
                                 }
                                 login = (userName == systemUser);
                                 }
                            }
                              
                         ]
                     } 
                     else Group{
                         content: [
              
              	   Text {
              	                 x: 10 y: 30
              	                 content: "You have successfully logged in."
              	              },
              	              SwingButton{
              	                 translateX: 10
              	                 translateY: 50
              	                 text: "Log out"
              	                 action: function(){
              	                  userName = "";
              	                  login = false;
              	               	}
              	              }
              	 
                   	  ]
                  }
             	} 
}

Running the application

In this section, you'll test the example Login application. Save the changes you've made so far.

  1. Right click on the Main.fx file and select Run As > JavaFX application. Leave the configuration settings with the defaults and click Run. A new window opens with the Login Application, as shown in Figure 8.
    Figure 8. Login Application
    A field for the user name is above the Submit button
  2. Enter abc and click Submit. The login fails, so you can see the error message logged in the console.
  3. Enter test and click Submit. The system accepts this user name and logs in successfully, as shown in Figure 9.
    Figure 9. Successful login
    The message 'You have successfully logged in' is visible above the Log out button

Creating an application to run on a mobile emulator

The LoginApp created above used the Desktop profile. In this section, create an application that uses a Mobile profile and runs on a mobile emulator. This example explores how to create animated graphics. You'll also render a circle that has varying opacity at different time intervals.

  1. Create a new JavaFX project. Click File > New > Project > JavaFX > JavaFX project.
  2. Enter the Project name AnimatedCircle, as shown in Figure 10. Select the Mobile profile.
    Figure 10. Login Application
    Another New JavaFX Project dialog box tracks the selections for the project AnimatedCircle

    Click Finish.

  3. Create a new package called com.sample.animation.
  4. Create a new empty JavaFX Script. Right click on the package and select New > Empty JavaFX Script.
  5. Enter Main as the Name, and click Finish.
  6. In the Snippets window, select the Applications tab to expand it.
  7. Select and drag the Stage object to the source editor.
  8. Enter Animated Circle as the Title. Leave the rest of the defaults as they are and click Insert.
  9. In the Snippets window, select the Basic Shapes tab to expand it.
  10. Select and drag the Circle element to the source editor inside the content[] element. Enter Color.BLUE as the fill property in the Insert Template dialog box, as shown in Figure 11.
    Figure 11. Adding a Circle
    By configuring the height and width values, you determine the size of the circle

    Click Insert.

  11. When adding a Linear Gradient pattern to the circle, you can specify two or more gradient colors. In the Snippets window, click the Gradients tab to expand it.
  12. Delete Color.BLUE from the fill value, then select and drag the Linear Gradient object to the source editor, as shown in Figure 12.
    Figure 12. Adding a Linear Gradient pattern to the circle
    The Linear Gradient object is visible on the right
  13. Now run the application to see what has developed so far. Save the changes. Right click on the Main.fx file and select Run As > JavaFX Application. The mobile emulator window will appear, displaying the circle with a linear gradient, as shown in Figure 13.
    Figure 13. Animated Circle App running in a mobile emulator
    The Animated Circle App runs in the mobile emulator

Adding animation support

Add animation support to the circle. The example walks through changing the opacity of the circle at different time intervals. You need a TimeLine that contains KeyFrames. The example has two keyframes: one that varies the opacity of the circle from 0.0 to 0.5 for 5 seconds, and one that varies the opacity from 0.5 to 1.0 in the next 10 seconds.

  1. Define a variable called opacity by adding the code in Listing 14.
    Listing 14. Declare global variable opacity
    var opacity = 1.0;
  2. Add a local variable for the circle and bind it to the global variable, as shown in Listing 15.
    Listing 15. Bind global variable to the circle's property opacity
     Circle {
          opacity : bind opacity;
          centerX: 100,
          centerY: 100,
          radius: 40,
  3. Add the TimeLine element. In the Snippets window, select the Animations tab to expand it. Drag the TimeLine element onto the editor. From the Insert Template dialog box, enter 5s for the time value, as shown in Figure 14.
    Figure 14. Adding a TimeLine
    The Time field is visible in the Timeline dialog box on the left

    Click Insert.

    Figure 15 shows the code that gets generated after dragging the TimeLine to the editor.

    Figure 15. TimeLine added
    The timeline wasg added to the code
  4. Drag the Values element from the Animations tab within the KeyFrame object after the canSkip attribute. In the Insert Template dialog, enter opacity for the variable value, as shown in Figure 16.
    Figure 16. Adding Values to a KeyFrame
    The Variable Name and Value are visible on the left

    Click Insert. In the generated code, shown in Figure 17, change the opacity value to 0.5.

    Figure 17. KeyFrame with Values added
    The change in opacity is marked with a red box in the code
  5. Add another KeyFrame, just below the KeyFrame in the example in Figure 17, with a time variable of 10 seconds and a Values element that changes the opacity to 1.0. The code should look similar to Figure 18.
    Figure 18. Timeline with two keyframes
    The timeline has two keyframes
  6. Finally, play the timeline. Add .play(), as shown in Figure 19.
    Figure 19. Playing the TimeLine
    The play command is marked with a red box in the code
  7. Run the application again to see the animated circle in action.

Summary

In this article, you learned about JavaFX and how to use it to quickly build GUI applications. The examples showed how to build forms using the Swing components. You also explored how to develop graphical applications and add animation support.


Downloads

DescriptionNameSize
Login Application Sample CodeLoginApp.zip23KB
Animated Circle Sample CodeAnimatedCircle.zip2KB

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, Java technology, Open source
ArticleID=550198
ArticleTitle=Use JavaFX to quickly create applications
publish-date=10122010