27
Use JavaFX to quickly create applications JavaFX + Eclipse IDE = Easy GUI Skill Level: Intermediate Ravikumar Vishwakarma ([email protected]) Software Engineer IBM Rohit P. Sardesai ([email protected]) Software Engineer IBM 12 Oct 2010 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. 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. Use JavaFX to quickly create applications Trademarks © Copyright IBM Corporation 2010. All rights reserved. Page 1 of 27

Use JavaFX to quickly create applications

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Use JavaFX to quickly create applications

Use JavaFX to quickly create applicationsJavaFX + Eclipse IDE = Easy GUI

Skill Level: Intermediate

Ravikumar Vishwakarma ([email protected])Software EngineerIBM

Rohit P. Sardesai ([email protected])Software EngineerIBM

12 Oct 2010

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

Overview

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

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

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

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 1 of 27

Page 2: Use JavaFX to quickly create applications

Installation

Follow these steps to download and install the JavaFX SDK and the JavaFX Eclipseplug-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:\ProgramFiles\JavaFX\javafx-sdk-version.

3. Start the Eclipse IDE. Provide a workspace name, such asC:/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, andhttp://javafx.com/downloads/eclipse-plugin/ for theLocation from which the plug-in needs to be installed.Figure 1. Add JavaFX Plug-in Site

Click OK.

7. Check the JavaFX feature that needs to be installed, as shown in Figure2.Figure 2. Check the JavaFX feature to be installed

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 2 of 27

Page 3: Use JavaFX to quickly create applications

Click Next.

8. The JavaFX feature version is displayed in the Install Details dialog. ClickNext.

9. Accept the terms of license agreements and click Finish.

10. Upon successful installation of the plug-in, restart the Eclipse workbenchwhen prompted.

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

Figure 3. Setting the JAVAFX_HOME classpath variable

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 3 of 27

Page 4: Use JavaFX to quickly create applications

Creating a Login application

In this section, build a sample JavaFX application to validate users against theirpasswords and allow them to log in to a system if they can provide the requiredcredentials. Upon successful authorization, the user will see a Welcome screen. Ifauthorization is not successful, a message in the Eclipse Console view will providethe 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

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 4 of 27

Page 5: Use JavaFX to quickly create applications

Click Next.

2. Enter LoginApp as the Project name. Select the Desktop profile. Theseselections are shown in Figure 5.Figure 5. Configuring the JavaFX project

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 5 of 27

Page 6: Use JavaFX to quickly create applications

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. Asshown in Listing 1, you need a Boolean variable called login thatmaintains the login state of the user (whether or not the last login wassuccessful). Declare the string variable username so that it holds theuser name entered by the user. There's also a hard-coded system usertest who can only log in to our application.Listing 1. Declaration of global variables

var login = false;var userName = "";var systemUser = "test";

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 6 of 27

Page 7: Use JavaFX to quickly create applications

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 Figure6. The Stage is the top-level container for holding the user interfaceJavaFX objects.Figure 6. Drag the Stage object onto the editor

9. Edit the title to be displayed for the Stage by entering Login App, asshown in Figure 7. Set both the width and the height to 300.Figure 7. Configuring the Stage object

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 7 of 27

Page 8: Use JavaFX to quickly create applications

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

10. Add a javafx.scene.Group element to the Scene with an importstatement, as shown in Listing 2. This group will act like a container forthe 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 {

}]

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 8 of 27

Page 9: Use JavaFX to quickly create applications

12. Begin adding child controls to the parent group control. First, add a labelby 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 inListing 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 theSwingTextField 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.

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 9 of 27

Page 10: Use JavaFX to quickly create applications

If the user name matches the system user, then the user successfullylogs in to the system. Import the JavaFX SwingButton using the importstatement 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 Textfield.

Listing 9. Add the SwingButton to the group

SwingButton{translateX: 50translateY: 50text: "Submit"action: function(){if((userName != systemUser)) {

println("Invalid UserName");}login = (userName == systemUser);}

}

15. The action function in Listing 9 checks if the userName that wasentered is the same as the system user name. If it is not, the exampleprints out the error message. Otherwise, the result is stored in the loginBoolean variable.So far you've handled the case where the login fails. You need to use thestate of the login variable to advance to the successful login screen. Thisdemands an if-else statement. Add the if-else clause, and in theelse clause, first add an empty group with a content object in it. Add thehighlighted 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

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 10 of 27

Page 11: Use JavaFX to quickly create applications

translateY: 50text: "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 Logout button that will return the user to the login screen. Import the Textclass, 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 elseclause group element you added earlier.Listing 12. Add the Text Class and SwingButton to the else group

Text {x: 10 y: 30content: "You have successfully logged in."

},SwingButton{

translateX: 10translateY: 50text: "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;

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 11 of 27

Page 12: Use JavaFX to quickly create applications

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: 300height: 300content: 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: 50translateY: 50text: "Submit"action: function(){

if((userName != systemUser)) {println("Invalid UserName");

}login = (userName == systemUser);}

}

]}else Group{

content: [

Text {x: 10 y: 30content: "You have successfully logged in."

},SwingButton{

translateX: 10translateY: 50text: "Log out"action: function(){userName = "";login = false;

}}

]}

}}

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 12 of 27

Page 13: Use JavaFX to quickly create applications

Running the application

In this section, you'll test the example Login application. Save the changes you'vemade 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 newwindow opens with the Login Application, as shown in Figure 8.Figure 8. Login Application

2. Enter abc and click Submit. The login fails, so you can see the errormessage logged in the console.

3. Enter test and click Submit. The system accepts this user name andlogs in successfully, as shown in Figure 9.Figure 9. Successful login

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 13 of 27

Page 14: Use JavaFX to quickly create applications

Creating an application to run on a mobile emulator

The LoginApp created above used the Desktop profile. In this section, create anapplication that uses a Mobile profile and runs on a mobile emulator. This exampleexplores how to create animated graphics. You'll also render a circle that hasvarying 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. Selectthe Mobile profile.Figure 10. Login Application

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 14 of 27

Page 15: Use JavaFX to quickly create applications

Click Finish.

3. Create a new package called com.sample.animation.

4. Create a new empty JavaFX Script. Right click on the package and selectNew > 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 asthey are and click Insert.

9. In the Snippets window, select the Basic Shapes tab to expand it.

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 15 of 27

Page 16: Use JavaFX to quickly create applications

10. Select and drag the Circle element to the source editor inside thecontent[] element. Enter Color.BLUE as the fill property in theInsert Template dialog box, as shown in Figure 11.Figure 11. Adding a Circle

Click Insert.

11. When adding a Linear Gradient pattern to the circle, you can specify twoor more gradient colors. In the Snippets window, click the Gradients tabto expand it.

12. Delete Color.BLUE from the fill value, then select and drag the LinearGradient object to the source editor, as shown in Figure 12.Figure 12. Adding a Linear Gradient pattern to the circle

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 16 of 27

Page 17: Use JavaFX to quickly create applications

13. Now run the application to see what has developed so far. Save thechanges. Right click on the Main.fx file and select Run As > JavaFXApplication. The mobile emulator window will appear, displaying thecircle with a linear gradient, as shown in Figure 13.Figure 13. Animated Circle App running in a mobile emulator

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 17 of 27

Page 18: Use JavaFX to quickly create applications

Adding animation support

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 18 of 27

Page 19: Use JavaFX to quickly create applications

Add animation support to the circle. The example walks through changing theopacity of the circle at different time intervals. You need a TimeLine that containsKeyFrames. The example has two keyframes: one that varies the opacity of thecircle from 0.0 to 0.5 for 5 seconds, and one that varies the opacity from 0.5 to 1.0 inthe 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, asshown 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 theAnimations tab to expand it. Drag the TimeLine element onto theeditor. From the Insert Template dialog box, enter 5s for the time value,as shown in Figure 14.Figure 14. Adding a TimeLine

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 19 of 27

Page 20: Use JavaFX to quickly create applications

Click Insert.

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

Figure 15. TimeLine added

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 20 of 27

Page 21: Use JavaFX to quickly create applications

4. Drag the Values element from the Animations tab within the KeyFrameobject after the canSkip attribute. In the Insert Template dialog, enteropacity for the variable value, as shown in Figure 16.Figure 16. Adding Values to a KeyFrame

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 21 of 27

Page 22: Use JavaFX to quickly create applications

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

Figure 17. KeyFrame with Values added

5. Add another KeyFrame, just below the KeyFrame in the example inFigure 17, with a time variable of 10 seconds and a Values element thatchanges the opacity to 1.0. The code should look similar to Figure 18.Figure 18. Timeline with two keyframes

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 22 of 27

Page 23: Use JavaFX to quickly create applications

6. Finally, play the timeline. Add .play(), as shown in Figure 19.Figure 19. Playing the TimeLine

7. Run the application again to see the animated circle in action.

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 23 of 27

Page 24: Use JavaFX to quickly create applications

Summary

In this article, you learned about JavaFX and how to use it to quickly build GUIapplications. The examples showed how to build forms using the Swingcomponents. You also explored how to develop graphical applications and addanimation support.

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 24 of 27

Page 25: Use JavaFX to quickly create applications

Downloads

Description Name Size Downloadmethod

Login Application Sample Code LoginApp.zip 23KB HTTP

Animated Circle Sample Code AnimatedCircle.zip 2KB HTTP

Information about download methods

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 25 of 27

Page 26: Use JavaFX to quickly create applications

Resources

Learn

• Get all the latest news and other information about JavaFX.

• Browse through the JavaFX Sample Gallery.

• Read JavaFX technical documentation and take tutorials.

• See JavaFX in action on the Vancouver 2010 Olympics site.

Get products and technologies

• Download JavaFX.

• Download IBM product evaluation versions or explore the online trials in theIBM SOA Sandbox and get your hands on application development tools andmiddleware products from DB2®, Lotus®, Rational®, Tivoli®, andWebSphere®.

Discuss

• Participate in developerWorks blogs and get involved in the developerWorkscommunity.

• Create your My developerWorks profile today and set up a watch list. Getconnected and stay connected with My developerWorks.

About the authors

Ravikumar VishwakarmaRavikumar Vishwakarma, a Staff Software Engineer at the IBM IndiaSoftware Lab in Mumbai, is part of the IBM WebSphere Content packProduct team. He has been involved with Content pack for more thanthree years. He currently uses IBM WebSphere BPM Stack products fordeveloping SOA applications. He is currently involved in creating BPMSolutions using IBM WebSphere Lombardi. Ravikumar has also workedon creating UIs using Lotus Forms Designer. You can reach him [email protected].

Rohit P. Sardesai

developerWorks® ibm.com/developerWorks

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 26 of 27

Page 27: Use JavaFX to quickly create applications

Rohit Sardesai works as a Staff Software Engineer in the IBM IndiaSoftware Lab and is a part of the Application and IntegrationMiddleware (AIM) team. His key technical skills involve Eclipse plug-indevelopment, OSGI, and Web 2.0 technologies (Dojo and REST). Hehas published an article series about building dynamic businessapplications using WebSphere Business Services Fabric (WBSF). He isalso actively involved in various Biztech projects. Currently, he isworking on BPM Repository and Clustering. You can reach Rohit [email protected].

ibm.com/developerWorks developerWorks®

Use JavaFX to quickly create applications Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 27 of 27