DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

  1. DZone
  2. Refcards
  3. Java FX
refcard cover
Refcard #156

Java FX

A Rich Client Platform for Java

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

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Stephen Chin
Lead Java Community Manager, Oracle
Table of Contents
► What is Java FX? ► JFX Poetry, a Simple Example ► Loading an Image ► Displaying Text with Effects ► Animated Transitions ► Interacting with Controls ► Finishing with Media ► FXML and CSS ► API Reference ► Additional Resources
Section 1

What is Java FX?

By Stephen Chin

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:

1
public class JFXPoetry extends Application {
2
      public static void main(String[] args) {
3
      launch(args);
4
      }
5
      @Override
6
      public void start(Stage stage) {
7
      stage.setTitle("Pippa's Song by Robert Browning");
8
      stage.setResizable(false);
9
      StackPane root = new StackPane();
10
      stage.setScene(new Scene(root, 500, 375));
11
      // add additional code here
12
      stage.show();
13
      }
14
      }

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:

4
1
Image image = new Image("http://farm1.static.flickr.
2
    com/39/121693644_75491b23b0.jpg");
3
    ImageView imageView = new ImageView(image);
4
    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.

15
1
Text text
2
    = new Text(
3
    "The year's at the spring,\n" +
4
    "And day's at the morn;\n" +
5
    "Morning's at seven;\n" +
6
    "The hill-side's dew-pearled;\n" +
7
    "The lark's on the wing;\n" +
8
    "The snail's on the thorn;\n" +
9
    "God's in His heaven--\n" +
10
    "All's right with the world!");
11
    text.setFont(Font.font("Serif", FontWeight.BOLD, 30));
12
    text.setFill(Color.GOLDENROD);
13
    text.setEffect(DropShadowBuilder.create().radius(3).spread(0.5).build());
14
    text.setCache(true);
15
    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:

7
1
final TranslateTransition translate = TranslateTransitionBuilder.create()    .duration(Duration.seconds(24))
2
    .node(text)
3
    .fromY(image.getHeight())
4
    .toY(0)
5
    .interpolator(Interpolator.EASE_OUT)
6
    .build();
7
    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.

13
1
Button play = new Button("Play Again");
2
    root.getChildren().add(play);
3
    play.visibleProperty().bind(translate.statusProperty()
4
      .isEqualTo(Animation.Status.STOPPED));
5
    play.addEventHandler(ActionEvent.ACTION,
6
                         new EventHandler<ActionEvent>() {
7
        @Override
8
        public void handle(ActionEvent event) {
9
            translate.playFromStart();
10
            sound.stop();
11
            sound.play();
12
        }
13
    });

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

14
1
<StackPane prefHeight="375" prefWidth="500"
2
    xmlns:fx="http://javafx.com/fxml"
3
    fx:controller="steveonjava.Controller">
4
    <children>
5
    <ImageView fx:id="imageView">
6
    <image>
7
    <Image fx:id="image" url="http://farm1.static.flickr.com/…"/>
8
    </image>
9
    </ImageView>
10
    <Text fx:id="text" cache="true" text="
11
    The year's at the spring,&#10;…"/>
12
    <Button fx:id="button" text="Play Again" onAction="#replay"/>
13
    </children>
14
    </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:

11
1
public class Controller implements Initializable {
2
    private TranslateTransition translate;
3
    private FadeTransition fade;
4
    private MediaPlayer mediaPlayer;
5
    @FXML private Text text;
6
    @FXML private Image image;
7
    @FXML private ImageView imageView;
8
    @FXML private Button button;
9
    @FXML private void replay(ActionEvent event) {…}
10
    @Override public void initialize(URL url, ResourceBundle rb) {…}
11
    }

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:

15
1
#text {
2
    -fx-font-family: serif;
3
    -fx-font-weight: bold;
4
    -fx-font-size: 30pt;
5
    -fx-fill: goldenrod;
6
    -fx-effect: dropshadow(three-pass-box, black, 3, .5, 0, 0);
7
    }
8
    #button {
9
    -fx-background-color: linear-gradient(darkorange, derive(darkorange, -80%));
10
    -fx-background-radius: 24;
11
    -fx-padding: 12;
12
    -fx-font-size: 16pt;
13
    -fx-font-weight: bold;
14
    -fx-text-fill: white;
15
    }

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:

3
1
Parent root = FXMLLoader.load( ().getResource("JFXPoetry.fxml"));
2
    Scene scene = new Scene(root);
3
    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/

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

Bye Bye JavaFX Scene Builder, Welcome Gluon Scene Builder 8.0.0
related article thumbnail

DZone Article

JavaFX Gets Video Capabilities
related article thumbnail

DZone Article

Styling a JavaFX Control with CSS
related article thumbnail

DZone Article

How to Merge HTML Documents in Java
related refcard thumbnail

Free DZone Refcard

Java Application Containerization and Deployment
related refcard thumbnail

Free DZone Refcard

Introduction to Cloud-Native Java
related refcard thumbnail

Free DZone Refcard

Java 15
related refcard thumbnail

Free DZone Refcard

Java 14

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: