Over a million developers have joined DZone.
Refcard #156

Java FX

A Rich Client Platform for Java

Written by

Stephen Chin Lead Java Community Manager, Oracle

Includes writing JavaFX applications and also serves as a convenient reference to some of the more advanced APIs in JavaFX 2.0.

Free PDF
DOWNLOAD
Section 1

What is Java FX?

JavaFX is an exciting new platform for building Rich Internet Applications with graphics, animation, and media. Starting with JavaFX 2.0, all the APIs are written in pure Java, which lets you write JavaFX applications directly in a language you are already familiar with. This Refcard will help you get started writing JavaFX applications and also serve as a convenient reference to some of the more advanced APIs.

To get started, download the latest JavaFX SDK from the JavaFX website at http://javafx.com/

If you are new to JavaFX, the easiest way to get started is to download the NetBeans bundle. This gives you full IDE support for writing JavaFX applications out of the box, including library setup, deployment options, and an integrated UI debugger. However, it is possible to do everything from your favorite IDE, such as Eclipse or IntelliJ, or the command line directly.

Section 2

JFX Poetry, a Simple Example

To illustrate how easy it is to build an application that melds graphics, text, animation, and media, we will start with a simple tutorial. The goal will be to write an application that:

  • Loads and displays an image from the internet
  • Displays and animates a verse of poetry
  • Makes use of graphic effects
  • Plays media asynchronously

For the JFXPoetry theme, we will use "Pippa's Song", a well known excerpt from Robert Browning's Pippa Passes.

Beginning with a Stage

Stage and Scene are the building blocks of almost every JavaFX program. A Stage can either be represented as a Frame for desktop applications or a rectangular region for applications embedded in a browser. The visual content of a Stage is called a Scene, which contains a parent node that is the root of a graph or tree of the rest of the elements called the scene graph. The following program creates a basic Stage and Scene with a StackPane layout as the root element:

public class JFXPoetry extends Application {
      public static void main(String[] args) {
      launch(args);
      }
      @Override
      public void start(Stage stage) {
      stage.setTitle("Pippa's Song by Robert Browning");
      stage.setResizable(false);
      StackPane root = new StackPane();
      stage.setScene(new Scene(root, 500, 375));
      // add additional code here
      stage.show();
      }
      }

This code illustrates the basic template for creating any JavaFX application. The necessary elements are:

  • A class that extends javafx.application.Application
  • A Java main method that calls the launch helper method
  • An implementation of the start method that takes the primary stage

The start method is guaranteed to be called on the JavaFX UI thread, so you can take care of scene graph manipulation and finally show the Stage when you are ready. Compiling and running this application will create a window with the title "Pippa's Song by Robert Browning" as shown in Figure 1.

Hot Tip

The JavaFX scene graph is an extremely powerful concept, which can be used to apply transformations and effects that change the rendering of all the child nodes.

html_titlebar

Figure 1. A simple Stage with a descriptive title

Section 3

Loading an Image

Loading and displaying images in JavaFX is extremely easy to do. The Image class allows you to load an image from a local file or a remote server simply by specifying the URL. This can then be set on an ImageView to be displayed inside of a Scene. The following code should be added before showing the Stage in replacement of the "add additional code here" comment:

Image image = new Image("http://farm1.static.flickr.
    com/39/121693644_75491b23b0.jpg");
    ImageView imageView = new ImageView(image);
    root.getChildren().add(imageView);

Notice that to add the Image element to the root StackPane, you must first get the list of children and then add an element. This is a common pattern used throughout the JavaFX APIs that is possible because of Observable Lists where any change to the list contents is automatically updated in the UI.

For the background image, we have chosen a picture of a misty morning in Burns Lake, BC, Canada taken by Duane Conlon. The running example can be seen in Figure 2.

network_loaded

Figure 2. Image loaded from the network

Section 4

Displaying Text with Effects

Displaying Text in JavaFX is as simple as constructing a Text Node and passing in a String to the constructor. There are many properties available on Text; however, for this example, we will set the font and fill color and add a Drop Shadow effect to make the text stand out on the background.

Text text
    = new Text(
    "The year's at the spring,\n" +
    "And day's at the morn;\n" +
    "Morning's at seven;\n" +
    "The hill-side's dew-pearled;\n" +
    "The lark's on the wing;\n" +
    "The snail's on the thorn;\n" +
    "God's in His heaven--\n" +
    "All's right with the world!");
    text.setFont(Font.font("Serif", FontWeight.BOLD, 30));
    text.setFill(Color.GOLDENROD);
    text.setEffect(DropShadowBuilder.create().radius(3).spread(0.5).build());
    text.setCache(true);
    root.getChildren().add(text);

Hot Tip

By using the cache property on Node, you can improve performance and avoid rendering artifacts during animation.

To create the DropShadow in the above code, we chose to use the builder syntax, which is a fluent API for creating JavaFX UI elements. Every JavaFX class has a builder peer that can be used to set properties by chaining method calls and will return an instance of the class when the final build method is invoked. This allows us to change the radius and spread properties of the DropShadow in order to accentuate the letters. Figure 3 shows the updated example with Text overlaid on the Image.

textoverlay

Figure 3. Updated example with a Text overlay

JavaFX offers a large set of graphics effects that you can easily apply to nodes to create rich visual effects. Table 1 lists all the available effects you can choose from.

Table 1. Graphics effects available in JavaFX

Transition Description
Blend Blends two inputs together using a pre-defined BlendMode
Bloom Makes brighter portions of the node appear to glow
BoxBlur Fast blur with a configurable quality threshold
ColorAdjust Per-pixel adjustments of hue, saturation, brightness, and
contrast
ColorInput Fills a rectangular region with the given Color
DisplacementMap Shifts each pixel by the amount specified in a displacement
map
DropShadow Displays an offset shadow underneath the node
GaussianBlur Blurs the node with a configurable radius
Glow Makes the node appear to glow with a given intensity level
ImageInput Passes an image through to a chained effect
InnerShadow Draws a shadow on the inner edges of the node
Lighting Simulates a light source to give nodes a 3D effect
MotionBlur Blurs the image at a given angle to create a motion effect
PerspectiveTransform Maps a node to an arbitrary quadrilateral for a perspective
effect
Reflection Displays an inverted view of the node to create a reflected
effect
SepiaTone Creates a sepia tone effect to mimic aged photographs
Shadow Similar to a DropShadow but without the overlaid image.
Section 5

Animated Transitions

Animations in JavaFX can be accomplished either by setting up a Timeline from scratch or by using one of the prefabricated Transitions. To animate the Text rising onto the screen, we will use a TranslateTransition, which adjusts the position of a node in a straight line for the specified duration:

final TranslateTransition translate = TranslateTransitionBuilder.create()    .duration(Duration.seconds(24))
    .node(text)
    .fromY(image.getHeight())
    .toY(0)
    .interpolator(Interpolator.EASE_OUT)
    .build();
    translate.play();

Hot Tip

Every JavaFX class has a matching builder, which you can use to make your code more readable when setting multiple properties.

By setting an interpolator of EASE_OUT, the text will start at full speed and gradually deaccelerate as it approaches its destination. To run the transition, all you need to do is call the play() function, which will animate the text as shown in Figure 4.

scroll_text

Figure 4. Animated Text Scrolling Into View

Before you use the WebSocket API, you need to make sure that the browser supports it. This way, you can provide a message, prompting the users of your application to upgrade to a more up-to-date browser. You can use the following code to test for browser support:

Table 2. Transitions Supported by JavaFX

Transition Description
FadeTransition Changes the opacity of a node over time
FillTransition Animates the fill color of a shape
ParallelTransition Plays a sequence of transitions in parallel
PathTransition Animates nodes along a Shape or Path
PauseTransition Executes an action after the specified delay
RotateTransition Changes the rotation of a node over time
ScaleTransition Changes the size of a node over time
SequentialTransition Plays a sequence of transitions in series
StrokeTransition Animates the stroke width of a shape
TranslateTransition Changes the position of a node over time
Section 6

Interacting with Controls

The JavaFX 2 release features a complete library of skinnable controls that give you everything you will need for most web and business applications. Table 3 lists some of the controls and what they can be used for.

Table 3. Controls Available in JavaFX 2

  Control Description
“Nodebox" Accordion The Accordion control lets you display a list of nodes that can be expanded by clicking the title. Since the title and content areas are both JavaFX nodes, you can embed images, controls, and even media in the accordion.
“Click Button JavaFX buttons are extremely versatile and have complete control over all aspects of style including color, text, shape, and even images.
“Checkbox" CheckBox The CheckBox control is a specialized type of button that includes a label text and a check selection area that can be checked, unchecked, or indeterminate, allowing for tri-state behavior.
“Choicebox" ChoiceBox A ChoiceBox allows selection from a list of pre-defined items using a drop-down menu. This control supports a null (or undefined) state and sets the selected item to something that is not in the list.
“Hyperlink" Hyperlink Hyperlinks are a special type of button that mimic the behavior of a hyperlink in a web browser. This includes rollover animation and a special style for visited links.
“Simple Label A label is a basic control for displaying read-only text.  It supports ellipses for content that is too long to be displayed and keyboard mnemonics for creating accessible UIs.
“List ListView The JavaFX ListView lets you display a vertical or horizontal list of items and is backed by an Observable List that will update automatically update the UI when the contents change. You can display Strings or any other type of object in a List by providing your own cell factory that converts objects into JavaFX nodes for display. Also, the list control supports single selection or multiple selection and lists where you can edit the contents inline.
“Progress ProgressBar The ProgressBar control gives feedback during long-running operations using a horizontal progress bar. This can either be as a percentage of complete when the duration is known or an indeterminate animation.
“Progress" ProgressIndicator The ProgressIndicator control has the same functionality as the ProgressBar, except it displays the progress either as a small pie graph or an indeterminate spinning animation.
“Radio RadioButton The JavaFX RadioButton behaves like a two-state checkbox when used alone, but it is more commonly added to a ToggleGroup where only one of a set of radio buttons can be active at a time.
“Table TableView The TableView is a very powerful table component for JavaFX that supports a two-dimensional grid of cells with column headers, column resizing, column reordering, multi-column sorting, nested columns, cell spans, editable cells, and many more features.
“Tab TabPane A TabPane displays a list of Tabs, only one of which can be active and displayed at a given time. The list can be positioned along the top, left, right, or bottom of the content area. If there are more tabs than fit, they will be displayed in a drop-down menu.
“Text

TextField/
TextArea/ PasswordField

JavaFX provides a complete set of editable text area controls, including a basic one-line TextField, a multi-line TextArea, and a specialized PasswordField that masks characters as they are entered.
“Tree TreeView The TreeView shows a hierarchical view of TreeItems with controls to allow each level to be expanded in place. To create a TreeView with multiple top-level nodes, you can set showRoot to false, which will hide the top-most element of the model. Like the ListView control, it supports custom cell factories to display different content types inline.

In addition to these controls, JavaFX also supports a ScrollPane, Separator, Slider, SplitPane, Tooltip, Menu, and HTMLEditor. All of the JavaFX controls are fully skinnable, allowing you to customize the look and feel to match the design of your application using CSS or a custom Skin class. The simplest control to use is a Button, which can easily be scripted to play the animation sequence again from the beginning. Adding a button to the scene is as simple as calling the constructor with the button text and adding it to the list of children.

Button play = new Button("Play Again");
    root.getChildren().add(play);
    play.visibleProperty().bind(translate.statusProperty()
      .isEqualTo(Animation.Status.STOPPED));
    play.addEventHandler(ActionEvent.ACTION,
                         new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            translate.playFromStart();
            sound.stop();
            sound.play();
        }
    });

To automatically hide the button while animation is in progress and show it after the animation completes, we make use of binding, a very powerful JavaFX feature that is exposed via a new set of APIs in JavaFX 2. By binding the visible property of the button to the animation status of the translation transition, the button will be shown as soon as the animation finishes.

Hot Tip

Binding is a great alternative for event listeners and callbacks, because it allows you to create dynamic content with very little code.


Following this, we make use of an ActionEvent handler to play the animation and the media from the start, which is triggered once the button shown in Figure 5 is clicked.

“Button

Figure 5: Button Control to Play the Animation Again

Section 7

Finishing with Media

The finishing touch is to add some audio to the scene. JavaFX has built-in media classes that make it very simple to play audio or video either from the local files or streaming off the network. To complete the example, we will add in a public domain clip of Indigo Bunting birds chirping in the background. Adding in the audio is as simple as creating a Media object with the source set to the URL and wrapping that in a MediaPlayer with autoPlay set to true.

final MediaPlayer sound = new MediaPlayer(new Media(
  "http://video.fws.gov/sounds/35indigobunting.mp3"));
sound.play();

Hot Tip

Besides loading media off a network, you can also access local files or resources in the application jar.

In this example, we are using an mp3 file, which is supported across platforms by JavaFX. Table 3 lists some of the common media formats supported by JavaFX, including all the cross-platform formats.

Table 3. Common Media Formats Supported by JavaFX

Type Format File Extension
Audio MPEG-1, 2, 2.5 Audio layer 3 mp3
Audio Waveform Audio Format wav
Audio Audio Interchange File Format aif, aiff
Video Flash Video: VP6 video with mp3 audio flv, f4v
Video FX Media: VP6 video with mp3 audio fxm

Note: This Refcard covers the latest changes through JavaFX 2.0.3. In addition to what is mentioned here, Oracle has announced support for AAC audio and H.264 video coming in JavaFX 2.1.

To try the completed example, complete with animation and audio, click the following url: http://steveonjava.com/refcard/JFXPoetry.jnlp

Section 8

FXML and CSS

In addition to writing applications in pure Java, JavaFX also supports a declarative markup format called FXML. Additionally, JavaFX lets you use CSS (cascading style sheets) to define control and component styles. The combination of FXML and CSS allows you to specify your user interface in a declarative and designer-friendly format while keeping your application logic in the Java language.

The following code snippet shows the JFXPoetry application converted to FXML

<StackPane prefHeight="375" prefWidth="500"
    xmlns:fx="http://javafx.com/fxml"
    fx:controller="steveonjava.Controller">
    <children>
    <ImageView fx:id="imageView">
    <image>
    <Image fx:id="image" url="http://farm1.static.flickr.com/…"/>
    </image>
    </ImageView>
    <Text fx:id="text" cache="true" text="
    The year's at the spring,&#10;…"/>
    <Button fx:id="button" text="Play Again" onAction="#replay"/>
    </children>
    </StackPane>

Notice that the element names match the JavaFX classes and that the attributes align with the properties of those classes. For complex types, you can instead specify them as nested elements, which allows you to create the scene graph hierarchy declaratively and specify complex types such as Images.

The fx namespace is defined in the root element and used to hook up a controller class that has the Java application logic to play the animations and media. The controller code is the same as shown earlier, so we have reduced the code to just the stub methods in the following listing:

public class Controller implements Initializable {
    private TranslateTransition translate;
    private FadeTransition fade;
    private MediaPlayer mediaPlayer;
    @FXML private Text text;
    @FXML private Image image;
    @FXML private ImageView imageView;
    @FXML private Button button;
    @FXML private void replay(ActionEvent event) {…}
    @Override public void initialize(URL url, ResourceBundle rb) {…}
    }

The variables annotated with @FXML will get their values injected by the elements in the FXML file with the matching fx:id tags. Any method in the controller can be hooked up as an event handler, which is demonstrated by the replay method that is wired up to the onAction event of the button element in the FXML. Finally, you can override the initialize method to do application setup after all the variables have been initialized, such as setting up the transitions, binding, and media for this poetry example.

The FXML file is complemented by a CSS file that defines the styles for the application elements, as shown in the following listing:

#text {
    -fx-font-family: serif;
    -fx-font-weight: bold;
    -fx-font-size: 30pt;
    -fx-fill: goldenrod;
    -fx-effect: dropshadow(three-pass-box, black, 3, .5, 0, 0);
    }
    #button {
    -fx-background-color: linear-gradient(darkorange, derive(darkorange, -80%));
    -fx-background-radius: 24;
    -fx-padding: 12;
    -fx-font-size: 16pt;
    -fx-font-weight: bold;
    -fx-text-fill: white;
    }

Note: Notice that the text fill is specified differently for a Text element (which inherits the Shape –fx-fill attribute) vs. a Button (which inherits the Control –fx-text-fill attribute)

JavaFX stylesheets are based on the W3C CSS2.1 specification with some additions inspired from CSS3. In addition, many JavaFX-specific properties are exposed by prefixing the property name with "-fx-", as shown in the above example to set the font size, fill, and drop shadow effect. In addition, the above CSS includes a new styling for the "Play Again" button so it matches the overall theme of the application better.

The final step is to load the FXML and CSS files in the start method of your application, as shown in the following code:

Parent root = FXMLLoader.load( ().getResource("JFXPoetry.fxml"));
    Scene scene = new Scene(root);
    scene.getStylesheets().add( ().getResource("JFXPoetry.css").toExternalForm());

Notice that the FXML loader expects a URL, while the stylesheet list on Scene is of type String. To convert a URL to a String for the stylesheet, you can call toExternalForm to get the correct URI syntax for the resource you are loading. Upon running you can see the new CSS button design as shown in Figure 6.

fxml button

Figure 6: FXML version of JFXPoetry with a CSS-styled button

To try the completed FXML example, complete with animation and audio, click the following url: http://steveonjava.com/refcard/JFXPoetry-FXML.jnlp

For both the Java and FXML versions of this application, you can find the source code on GitHub: https://github.com/steveonjava/JFXPoetry

Hot Tip

If you are a JVM language fan, you can also code your application in Scala, Groovy, Visage, or other languages that compile to JVM
Section 9

API Reference

An easy way to view and navigate the full JavaFX API is to use the Ensemble sample application. This comes with the JavaFX SDK and can be launched by double clicking the Ensemble.jar in the samples folder. Figure 7 shows what the Ensemble application looks like when you first open it.

“JavaApp&quot;

Figure 7: JavaFX Ensemble application

Ensemble comes with live code samples of all the major features of JavaFX as well as an inline API documentation viewer, which makes use of the new WebView component that provides a full-featured, embeddable browser that you can use in your own applications.

Section 10

Additional Resources

  • JavaFX API documentation: http://docs.oracle.com/javafx/2.0/
    api/index.html

  • JavaFX FXML introduction: http://docs.oracle.com/javafx/2.0/
    api/javafx/fxml/doc-files/introduction_to_fxml.html

  • JavaFX CSS reference guide: http://docs.oracle.com/javafx/2.0/
    api/javafx/scene/doc-files/cssref.html

  • JFXtras, utilities and add-ons for JavaFX: http://jfxtras.org/

  • Pro JavaFX Platform 2 book with free samples for download:
    http://projavafx.com/

  • Examples and news direct from the JavaFX team: http://
    fxexperience.com/

  • My blog covering all things JavaFX: http://steveonjava.com/

  • Compatible JVM language libraries:

  • Scala language bindings: http://scalafx.org/

  • Groovy language bindings: http://groovyfx.org/

  • Visage UI language: http://visage-lang.org/

Publications

  • Featured
  • Latest
  • Popular
DOWNLOAD
Design Patterns
Learn design patterns quickly with Jason McDonald's outstanding tutorial on the original 23 Gang of Four design patterns, including class diagrams, explanations, usage info, and real world examples.
198.9k 535.8k
DOWNLOAD
Core Java
Gives you an overview of key aspects of the Java language and references on the core library, commonly used tools, and new Java 8 features.
122.2k 321.6k
DOWNLOAD
Getting Started with Ajax
Introduces Ajax, a group interrelated techniques used in client-side web development for creating asynchronous web applications.
100.4k 196.6k
DOWNLOAD
Getting Started with Git
This updated Refcard explains why so many developers are migrating to this exciting platform. Learn about creating a new Git repository, cloning existing projects, the remote workflow, and more to pave the way for limitless content version control.
108.7k 241.8k
DOWNLOAD
Spring Configuration
Catalogs the XML elements available as of Spring 2.5 and highlights those most commonly used: a handy resource for Spring context configuration.
101.7k 254k
DOWNLOAD
Core CSS: Part I
Covers Core principles of CSS that will expand and strengthen your professional ability to work with CSS. Part one of three.
88.7k 191.5k
DOWNLOAD
jQuery Selectors
Introduces jQuery Selectors, which allow you to select and manipulate HTML elements as a group or as a single element in jQuery.
92k 347.8k
DOWNLOAD
Foundations of RESTful Architecture
Introduces the REST architectural style, a worldview that can elicit desirable properties from the systems we deploy.
90.6k 132.9k
DOWNLOAD
The Ultimate Scrum Reference Card
Provides a concise overview of roles, meetings, rules, and artifacts within a Scrum organization. Updated for 2016.
84.5k 222.5k
DOWNLOAD
Core Java Concurrency
Helps Java developers working with multi-threaded programs understand the core concurrency concepts and how to apply them.
88.1k 179.3k
DOWNLOAD
Core CSS: Part II
Covers Core principles of CSS that will expand and strengthen your professional ability to work with CSS. Part two of three.
72.3k 137.8k
DOWNLOAD
Getting Started with Eclipse
Gives insights on Eclipse, the leading IDE for Java, which has a rich ecosystem of plug-ins and an open-source framework that supports other languages.
72k 182.6k
{{ card.title }}
{{card.downloads | formatCount }} {{card.views | formatCount }}

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}