Skip to main content

Create rich applications with JavaFX Script

Your guide to JavaFX Script essentials

Cathy Kegley (ckegley@us.ibm.com), Software Engineer, IBM
Cathy Kegley is a Software Engineer for IBM on the Lotus Expeditor client team.
Greg Roberts (gwrobert@us.ibm.com), Staff Software Engineer, IBM
Greg Roberts is a Staff Software Engineer for IBM on the Lotus Expeditor client development team.

Summary:  JavaFX Script, which made its debut last spring, is a scripting language that runs on top of Java™ Platform, Standard Edition 6 (Java SE) and makes it easy to code sophisticated user interfaces. Learn the essentials of the JavaFX scripting language and gain an understanding of some basic UI components with the help of the sample application detailed within.

Date:  15 Jan 2008
Level:  Intermediate
Activity:  15401 views

JavaFX Script is a scripting language designed to facilitate the creation of rich client and Internet applications. The language is highly portable and can run on any system that supports Java technology, without local installation. It uses underlying Java technologies to let you create GUIs of any size or complexity easily.

This article walks you through the basics of the JavaFX Script language and uses a sample application to introduce some UI components. To benefit from the article, you should have a strong understanding of the Java programming language and development experience with Swing.

JavaFX Script licensing

JavaFX Script, as of this writing, is one of a family of JavaFX products from Sun Microsystems. (The only other family member currently is JavaFX Mobile, an operating and application environment for Java technology-enabled devices.) Sun has announced that JavaFX Script will be licensed under the GNU Public License v2 in the future. Meanwhile, the JavaFX Community is built around sharing early versions of the JavaFX Script language and collaborating on its development (see Resources).

Before you start with JavaFX Script

When you develop applications with JavaFX Script, it's useful to have a JavaFX Script development environment installed. Some IDEs designed specifically for JavaFX Script, as well as JavaFX Script plug-ins for other Java development environments, are available. For this article, we recommend the JavaFX Script plug-in for Eclipse (see Resources for information about this and other development options).


JavaFX Script overview

JavaFX Script is a statically typed language, which means that the data type of every variable, parameter, and method return value is known at compile time. JavaFX Script is also a declarative programming language: it describes what the application is like rather than how to create it. The algorithm that determines how to display the application on the screen is left to the support software (Swing's Java 2D APIs). Because of these traits, JavaFX Script is well suited for GUI creation.

To help you understand the sample application code and the JavaFX Script GUI components it uses, we'll start by outlining a few basics of the JavaFX Script syntax.

Variables and primitive types

JavaFX Script provides four primitive types: String, Boolean, Number, and Integer. Table 1 shows the Java types they correspond to:


Table 1. JavaFX Script primitive types and their Java counterparts
JavaFX Script primitive typesCorresponding Java primitive or object
Stringjava.lang.String
Booleanjava.lang.Boolean
Numberjava.lang.Number
Integerint, long, byte, short, java.math.BitInteger

A variable of any of these types is introduced with the var keyword. Unlike the Java language, JavaFX Script does not require you to specify a variable's type in its declaration. The interpreter can infer variable type based on its use. However, because JavaFX Script is statically typed, a declared variable's type must remain the same throughout its life cycle. For example, var myString = "Hello"; in JavaFX Script is equivalent to var myString:String = "Hello"; in Java code.

Operators

Tables 2 and 3 list the operators used in JavaFX Script and their Java equivalents. You can refer to these tables when you create expressions in JavaFX Script.


Table 2. JavaFX Script relational operators
Relational operatorsJava equivalentMeaning
====Equal
<>!=Not equal
<<Less than
>>Greater than
<=<=Less than or equal
>=>=Greater than or equal

Table 3. JavaFX Script Boolean operators
Boolean operatorsJava equivalentMeaning
and&&Logical and
or||Logical or
not!Not

Functions and operations

JavaFX Script uses the function keyword to represent a functional subset of the program. In JavaFX Script, a function can contain variable declarations and a return statement, all contained within curly braces. This is ideal for simple mathematical functions or class getters and setters. Listing 1 shows an example of a JavaFX Script function that adds two numbers:


Listing 1. Sample function
function add(a,b) {
   var c = a + b;
   return c;
}

All procedures in JavaFX Script are denoted by the operation keyword and can contain any number of statements. Listing 2 shows an example of a simple operation:


Listing 2. Sample operation
operation helloWorld() {
   System.out.println("Hello world.");
}


JavaFX Script sample application

To demonstrate some of JavaFX Script's basic GUI capabilities, we've created a simple calculator application with a subset of the functionality you find on the system calculator included with the Microsoft® Windows® operating system. Figure 1 shows the calculator:


Figure 1. JavaFX Script calculator
JavaFX Script calculator

Frames and menus

The display of a JavaFX Script application is represented by a Frame object. It is a top-level window with a border, title, and optional menu bar. Listing 3 shows the declaration of the calculator's frame:


Listing 3. Frame declaration
Frame {
   menubar: MenuBar {
      ...
   }
   //text displayed in title bar
   title: "Calculator"
   //size of frame
   height: 200
   width: 200
   //begin content layout
   content: GridBagPanel {
      ...
   }
   visible: true
}

In JavaFX Script, an object's attributes are defined within their declaration. In Listing 3, menubar, title, height, width, content, and visible are all attributes of the Frame object. The title attribute contains a String value that is shown in the window's title bar. We have set this value to Calculator. (Notice the title in Figure 1.) The height and width attributes define the window's size in pixels. visible is a Boolean attribute that determines whether or not the frame is visible upon initial rendering.

The menubar attribute declared in the Frame object in Listing 3 has a MenuBar object as its value. This MenuBar object can contain one or more Menu objects that define the name and contents of the menus found along the top of the calculator window. Our application declares a File menu containing one operation: Exit. Its declaration is shown in Listing 4:


Listing 4. Menu declaration
menubar: MenuBar {
   menus: Menu {
      text: "File"
      //first item in the menu
      items: MenuItem {
         text: "Exit"
         //on-click operation
         action: operation() {
            //exit the application
            System.exit(0);
         }
      }
   }
}

The Menu object has a text attribute whose value is a String representing the title of the menu to be displayed — File in this case. The Menu object also contains an attribute called items whose value can be one or more MenuItem objects. A MenuItem represents an operation found in the current menu. The text attribute defines the name of the MenuItem, and the action attribute contains an operation that determines the item's behavior. When a user of our calculator application selects File > Exit, the operation defined in the action attribute is executed, and the application exits.

Layouts and borders

Refer again to the Frame declaration in Listing 3. The content attribute is perhaps the most important of the Frame object's attributes. Its value is a widget object that defines the content to be displayed within the window below the title and menu bars. The calculator's text field and buttons are created within the content attribute. To organize the buttons on the calculator in an orderly fashion, we've created a formatted panel, as shown in Listing 5:


Listing 5. GridBagPanel declaration
content: GridBagPanel {
   border: EmptyBorder {
      ...
   }
   cells: {
      ...
   }
}

JavaFX Script layout managers encapsulate corresponding Swing/AWT layouts and instantiate a JPanel instance with the specified layout manager. Components are then added to the JPanel through the attributes provided by the JavaFX Script object. Table 4 shows the JavaFX Script widgets and each one's corresponding Swing/AWT layout manager:


Table 4. JavaFX Script layouts
JavaFX Script widgetSwing layout manager
BoxBoxLayout
BorderPanelBorderLayout
CardPanelCardLayout
FlowPanelFlowLayout
GridBagPanelGridBagLayout
GridPanelGridLayout
GroupPanelGroupLayout
StackPanelRomain Guy's StackLayout

Similarly, each JavaFX Script border encapsulates a Swing border object. Each JavaFX Script border has attributes that correspond to that Swing border's configuration options. Table 5 displays the corresponding borders:


Table 5. JavaFX Script borders
JavaFX Script borderSwing border
BevelBorderBevelBorder
EmptyBorderEmptyBorder
LineBorderLineBorder
MatteBorderMatteBorder
SoftBevelBorderSoftBevelBorder
TiltedBorderTiltedBorder

As you saw in Listing 5, we use a GridBagPanel for the calculator application. The GridBagPanel aligns components in a grid format (vertically and horizontally) without requiring that the components be the same size. Each GridBagPanel maintains a grid of cells, with each component taking up one or more cells. The GridBagPanel has two attributes: border and cells. The border attribute defines the type of border (one of the objects in Table 5) that's displayed in the GridBagPanel. For the calculator application, we choose to use an EmptyBorder object, as shown in Listing 6:


Listing 6. EmptyBorder declaration
border: EmptyBorder {
   top: 5
   left: 5
   bottom: 5
   right: 5
}

The empty border is completely transparent. It takes up space as defined by the border attributes but does no drawing. The attributes of the EmptyBorder are top, left, bottom, and right. Their values define the amount of space, in pixels, that the border takes up on each side of the display. In this case, we reserve five pixels as a transparent border between the grid components and each edge of the panel display.

The GridPanel's cells attribute defines the components within the grid display. This attribute's value is an array of GridCell objects. Each GridCell object represents a single component within the grid. The GridCell attributes dictate how the object should be displayed and where it is positioned within the panel. Our calculator application contains 19 GridCell objects. One GridCell corresponds to the text field at the top of the calculator, 2 correspond to the Back and Clear buttons, and 16 correspond to the number and operation buttons shown on the calculator in Figure 1. Listing 7 shows the GridCell objects for the calculator's text field, the Back and Clear buttons, and the first two numbers:


Listing 7. GridCell declarations
cells:
      [ GridCell {
         anchor: WEST
         fill: HORIZONTAL
         //horizontal grid position
         gridx: 0
         //vertical grid position
         gridy: 0
         //column span
         gridwidth: 4
         content: textField
      }, GridCell {
         anchor: WEST
         fill: HORIZONTAL
         gridx: 0
         gridy: 1
         gridwidth: 2
         content: Button {
            text: "Back"
            ...
         }
      }, GridCell {
         anchor: WEST
         fill: HORIZONTAL
         gridx: 2
         gridy: 1
         gridwidth: 2
         content: Button {
            text: "Clear"
            ...         
         }
      }, GridCell {
         anchor: WEST
         fill: HORIZONTAL
         gridx: 0
         gridy: 2
         content: Button {
            text: "7"
            ...
         }
      }, GridCell {
         anchor: WEST
         fill: HORIZONTAL
         gridx: 1
         gridy: 2
         content: Button {
            text: "8"
            ...
         }
      }]

As you can see in Listing 7, every GridCell object contains five attributes: anchor, fill, gridx, gridy, and content. The anchor attribute is used when the component is smaller than its display area and dictates where within the display area to place the component. The possible values are NORTH, SOUTH, EAST, WEST, NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST, and CENTER.

The fill attribute is also used when the component's display area is larger than the component. It dictates how to resize the component, if at all. Table 6 describes the possible values:


Table 6. GridCell fill values
ValueBehavior
NONEDefault value. Take no action.
HORIZONTALMake the component wide enough to fill the horizontal display area. Do not change its height.
VERTICALMake the component tall enough to fill the vertical display area. Do not change its width.
BOTHMake the component tall enough and wide enough to fill both the horizontal and vertical display areas.

All components within the calculator are anchored to the west and fill their spaces horizontally.

The gridx and gridy attributes of the GridCell define the location of the component within the grid. These values specify the cell containing the leading corner of the component's display area, with the origin cell having the location of gridx = 0, gridy = 0.

Three of the GridCell components defined in Listing 7 also contain the gridwidth attribute. This attribute specifies the number of cells in the grid row that the component should occupy. For example, the first GridCell object in Listing 7 (the calculator's text field) has a gridwidth of 4. This value dictates that the text-field component should span four columns. Its gridx and gridy values are both 0, which indicate that the leftmost corner of the text field's display area should begin in the first row and first column of the grid area.

Text fields and buttons

Each GridCell component defined in Listing 7 contains a widget value that defines what's drawn in the cell's display area. The cells within our calculator application contain text-field and button widgets.

In Listing 7, we define new objects directly in the content attribute. Now we'll show JavaFX Script's versatility in an alternate scenario by defining the text field as a variable called textField outside of the content attribute. This declaration is shown in Listing 8. Once the text field is defined, the content attribute of the GridCell for the text field can contain just the variable name as its value.


Listing 8. TextField declaration
var textField = TextField {
   //indicates default value to appear in text field
   value: "."
   //indicates justification
   horizontalAlignment: TRAILING
   onChange: operation(s:String) {
      //don't change value if user types an invalid character   
   }
};

The TextField object has four attributes. The value attribute defines the default value that should appear in the text field. The horizontalAlignment attribute indicates the justification of the text field's contents. Table 7 describes the possible values for the horizontalAlignment attribute:


Table 7. TextField alignment values
ValueDescription
TRAILINGIndicates right justification.
LEADINGIndicates left justification.
CENTERIndicates center justification.

The calculator application has a text field with right justification, specified by the TRAILING keyword.

The text-field widget's onChange attribute contains an operation that determines what occurs when the user changes the text field's content. Here's where the calculator application checks for invalid characters.

Buttons can be defined in much the same way as a text field. You can declare a button first as a variable or define it directly in the parent object's content attribute. Listing 9 displays the definition of the Back button:


Listing 9. Button declaration
content: Button {
text: "Back"
   action: operation() {
      //remove last character entered
   }
}

The Button widget contains two attributes: text and action. The value of text indicates what's displayed on the button. The action attribute contains an operation that dictates what occurs when a user clicks on the defined button. In this case, the Back button should remove the last character entered into the text field defined in Listing 8.

A number of widgets can be used in a JavaFX Script UI aside from one ones in the calculator example. See Resources for links to more information on the layouts and widgets we've presented here as well as additional GUI components.


Conclusion

JavaFX Script is a highly dynamic and portable language that has the power to create extensive GUI applications similar to those created with Swing, but with a much smaller footprint. Although JavaFX Script differs in syntax from Java code, much of the underlying technology is the same. We encourage you to explore JavaFX Script and its capabilities further and use the knowledge you gained here to create a JavaFX Script application of your own.


Resources

Learn

Get products and technologies

Discuss

About the authors

Cathy Kegley is a Software Engineer for IBM on the Lotus Expeditor client team.

Greg Roberts is a Staff Software Engineer for IBM on the Lotus Expeditor client development team.

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology, Web development
ArticleID=281659
ArticleTitle=Create rich applications with JavaFX Script
publish-date=01152008
author1-email=ckegley@us.ibm.com
author1-email-cc=jaloi@us.ibm.com
author2-email=gwrobert@us.ibm.com
author2-email-cc=jaloi@us.ibm.com

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers