Home > Articles > Web Development

  • Print
  • + Share This
This chapter is from the book

3.2 Building JavaFX Programs

Let’s begin with a simple, graphical example of JavaFX shown Figure 3.2. This application consists of a rounded rectangle geometric shape and a text node. The rectangle has a drop shadow effect and the text node includes a “reflection” effect. The top-level node is a layout node (a StackPane) that stacks and centers its children nodes on top of each other. Let’s show you one way to build this program.

Figure 3.2

Figure 3.2 MyRectangleApp running

Figure 3.3 shows a diagram of the (partial) JavaFX class hierarchy for the Rectangle, Text, and StackPane classes used in the MyRectangleApp application. Rectangle, Text, and Circle (which we’ll use in a later example) are all subclasses of Shape, whereas StackPane is a subclass of Parent, a type of node that manages child nodes.

Figure 3.3

Figure 3.3 JavaFX node class hierarchy (partial) used in MyRectangleApp

Creating a JavaFX Application

To build the MyRectangleApp application with the NetBeans IDE, use these steps.

  1. In the NetBeans IDE, select File | New Project. NetBeans displays the Choose Project dialog. Under Categories, select JavaFX and under Projects, select JavaFX Application, as shown in Figure 3.4. Click Next.

    Figure 3.4

    Figure 3.4 Creating a new JavaFX Application

  2. NetBeans displays the Name and Location dialog. Specify MyRectangleApp for the Project Name. Click Browse and navigate to the desired project location. Accept the defaults on the remaining fields and click Finish, as shown in Figure 3.5.

    Figure 3.5

    Figure 3.5 New JavaFX application: Name and Location dialog

NetBeans builds a “starter” Hello World project for you with a Button and event handler. Figure 3.6 shows the project’s structure, Java file MyRectangleApp.java in package myrectangleapp. NetBeans brings MyRectangleApp.java up in the Java editor. Let’s replace the code in the start() method to build the application shown in Figure 3.2 on page 87.

Figure 3.6

Figure 3.6 MyRectangleApp Projects view

Java APIs

JavaFX, like Swing, lets you create objects and configure them with setters. Here’s an example with a Rectangle shape.

            Rectangle rectangle = new Rectangle(200, 100, Color.CORNSILK);
            rectangle.setArcWidth(30);
            rectangle.setArcHeight(30);
            rectangle.setEffect(new DropShadow(10, 5, 5, Color.GRAY));

This code example creates a Rectangle with width 200, height 100, and color Color.CORNSILK. The setters configure the arcWidth and arcHeight properties (giving the rectangle a rounded appearance) and add a gray drop shadow effect.

Similarly, we create a Text object initialized with the text “My Rectangle.” The setters configure the Text’s font and effect properties with Font and Reflection objects, respectively.

            Text text = new Text("My Rectangle");
            text.setFont(new Font("Verdana Bold", 18));
            text.setEffect(new Reflection());

The layout control is a StackPane for the top-level node. Here we use the StackPane’s default configuration, which centers its children, and specify a preferred height and width. Note that StackPane keeps its children centered when you resize the window. You add nodes to a layout control (a Pane) with getChildren().add() for a single node and getChildren().addAll() for multiple nodes, as shown here. (The getChildren() method returns a JavaFX Collection.)

        StackPane stackPane = new StackPane();
        stackPane.setPrefHeight(200);
        stackPane.setPrefWidth(400);
        stackPane.getChildren().addAll(rectangle, text);

Since the rectangle is added to the StackPane first, it appears behind the text node, which is on top. Adding these nodes in the reverse order would hide the text node behind the rectangle.

JavaFX has other layout controls including HBox (horizontal box), VBox (vertical box), GridPane, FlowPane, AnchorPane, and more.

Listing 3.1 shows the complete source for program MyRectangleApp.

Listing 3.1 MyRectangleApp.java2

package myrectangleapp;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class MyRectangleApp extends Application {

    @Override
    public void start(Stage primaryStage) {

        Rectangle rectangle = new Rectangle(200, 100, Color.CORNSILK);
        rectangle.setArcWidth(30);
        rectangle.setArcHeight(30);
        rectangle.setEffect(new DropShadow(10, 5, 5, Color.GRAY));

        Text text = new Text("My Rectangle");
        text.setFont(new Font("Verdana Bold", 18));
        text.setEffect(new Reflection());

        StackPane stackPane = new StackPane();
        stackPane.setPrefHeight(200);
        stackPane.setPrefWidth(400);
        stackPane.getChildren().addAll(rectangle, text);

        final Scene scene = new Scene(stackPane, Color.LIGHTBLUE);
        primaryStage.setTitle("My Rectangle App");

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // main() is invoked when running the JavaFX application from NetBeans
    // but is ignored when launched through JavaFX deployment (packaging)
    public static void main(String[] args) {
        launch(args);
    }
}

Figure 3.7 depicts the scene graph for program MyRectangleApp. Stage is the top-level window and is created by the JavaFX Platform. Every Stage has a Scene which contains a root node. In our example, the StackPane is the root node and its children include the Rectangle and the Text nodes. Note that StackPane is a parent node and Rectangle and Text are leaf nodes.

Figure 3.7

Figure 3.7 The JavaFX scene graph for MyRectangleApp

Using CSS

We’re not quite finished with our example. Figure 3.8 shows the same program with a linear gradient added to the rectangle. Originally, we built the rectangle with fill color Color.CORNSILK. Now let’s use CSS to configure the rectangle’s fill property with a linear gradient that gradually transforms from a light orange to a dark orange in a rich-looking fill, as shown in Figure 3.8.

Figure 3.8

Figure 3.8 Applying a linear gradient

(You’ll have to trust our description or run the program, since the book’s black and white print medium lacks color.)

To create this linear gradient, we apply a CSS style with the setStyle() method. This CSS specifies style element -fx-fill, which is the JavaFX-specific CSS style for a Shape’s fill property.

            rectangle.setStyle("-fx-fill: "
                + "linear-gradient(#ffd65b, #e68400),"
                + "linear-gradient(#ffef84, #f2ba44),"
                + "linear-gradient(#ffea6a, #efaa22),"
                + "linear-gradient(#ffe657 0%, #f8c202 50%, #eea10b 100%),"
                + "linear-gradient(from 0% 0% to 15% 50%, "
                + "rgba(255,255,255,0.9), rgba(255,255,255,0));");

This style defines five linear gradient elements.3

The ability to style nodes with CSS is an important feature that allows graphic designers to participate in styling the look of a program. You can replace any or all of the styles in the JavaFX default CSS file and add your own on top of the default styles.

Creating a JavaFX FXML Application

A helpful structural tool with JavaFX is to specify JavaFX scene graph nodes with FXML. FXML is an XML markup language that fits nicely with the hierarchical nature of a scene graph. FXML helps you visualize scene graph structures and lends itself to easier modification that can otherwise be tedious with Java code.

FXML typically requires three files: the program’s main Java file, the FXML file, and a Java controller class for the FXML file. The main Java class uses an FXML Loader to create the Stage and Scene. The FXML Loader reads the FXML file and builds the scene graph. The controller class provides JavaFX node initialization code and accesses the scene graph programmatically to create dynamic content or handle events.

Let’s redo our previous application and show you how to use FXML. You can create a JavaFX FXML Application with the NetBeans IDE using these steps.

  1. From the top-level menu, select File | New Project. NetBeans displays the Choose Project dialog. Under Categories, select JavaFX and under Projects, select JavaFX FXML Application, as shown in Figure 3.9. Click Next.

    Figure 3.9

    Figure 3.9 Creating a JavaFX FXML application project

  2. NetBeans displays the Name and Location dialog. Provide MyRectangleFXApp for the Project Name, click Browse to select the desired location, and specify MyRectangleFX for the FXML document name, as shown in Figure 3.10. Click Finish.

    Figure 3.10

    Figure 3.10 Specifying the project and FXML file name

NetBeans creates a project consisting of three source files: MyRectangleFXApp.java (the main program), MyRectangleFX.fxml (the FXML document), and MyRectangleFXController.java (the controller class).

Listing 3.2 shows the structure of the new main program. Note that the FXML Loader reads in the FXML file, MyRectangleFX.fxml, and builds the scene graph.

Listing 3.2 MyRectangleFXApp.java

package myrectanglefxapp;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class MyRectangleFXApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource(
                        "MyRectangleFX.fxml"));
        Scene scene = new Scene(root, Color.LIGHTBLUE);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Figure 3.11 shows the structure of a JavaFX FXML Application. Execution begins with the main program, which invokes the FXML Loader. The FXML Loader parses the FXML document, instantiates the objects, and builds the scene graph. After building the scene graph, the FXML Loader instantiates the controller class and invokes the controller’s initialize() method.

Figure 3.11

Figure 3.11 Structure of a JavaFX FXML Application

Now let’s look at the FXML markup for this application, as shown in Listing 3.3. Each FXML file is associated with a controller class, specified with the fx:controller attribute (marked in bold). With XML markup, you see that the structure of the FXML matches the hierarchical layout depicted in Figure 3.7 on page 92 (that is, starting with the root node, StackPane). The StackPane is the top node and its children are the Rectangle and Text nodes. The Rectangle’s properties are configured with property names and values that are converted to the correct types. The style property matches element -fx-fill we showed you earlier. (Fortunately, you can break up strings across lines in CSS.)

Both the Rectangle and Text elements have their effect properties configured. The Rectangle has a drop shadow and the Text element has a reflection effect.

Listing 3.3 MyRectangleFX.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.effect.*?>

<StackPane id="StackPane" prefHeight="200" prefWidth="400"
           xmlns:fx="http://javafx.com/fxml"
           fx:controller="myrectanglefxapp.MyRectangleFXController">
    <children>
        <Rectangle fx:id="rectangle" width="200" height="100"
                   arcWidth="30" arcHeight="30"
                   style="-fx-fill: linear-gradient(#ffd65b, #e68400),

            linear-gradient(#ffef84, #f2ba44),
            linear-gradient(#ffea6a, #efaa22),
            linear-gradient(#ffe657 0%, #f8c202 50%, #eea10b 100%),
            linear-gradient(from 0% 0% to 15% 50%, rgba(255,255,255,0.9),
            rgba(255,255,255,0));" >
            <effect>
                <DropShadow color="GRAY" offsetX="5.0" offsetY="5.0" />
            </effect>
        </Rectangle>
        <Text text="My Rectangle">
            <effect>
                <Reflection />
            </effect>
            <font>
                <Font name="Verdana Bold" size="18.0" />
            </font>
        </Text>
    </children>
</StackPane>

To access FXML elements from the controller class, give them an fx-id tag. Here, we’ve assigned the Rectangle element fx:id="rectangle" (marked in bold). This references a class variable that you declare in the controller class.

Now let’s show you the controller class. Listing 3.4 displays the source for MyRectangleFXController.java.

Annotation @FXML marks variable rectangle as an FXML-defined object. The initialize() method is invoked after the scene graph is built and typically includes any required initialization code. Here we configure two additional Rectangle properties, strokeWidth and stroke. While we could have configured these properties in the FXML file, Listing 3.4 shows you how to access FXML-defined elements in the controller class.

Listing 3.4 MyRectangleFXController

package myrectanglefxapp;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;

import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

public class MyRectangleFXController implements Initializable {

    @FXML
    private Rectangle rectangle;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        rectangle.setStrokeWidth(5.0);
        rectangle.setStroke(Color.GOLDENROD);
    }
}

The controller class also includes event handlers (we’ll add an event handler when we show you animation). Figure 3.12 shows MyRectangleFXApp running with the Rectangle’s stroke and strokeWidth properties configured.

Figure 3.12

Figure 3.12 Rectangle’s customized stroke and strokeWidth properties

CSS Files

Instead of specifying the hideously long linear gradient style in the FXML file (see Listing 3.3 on page 96), let’s hide this code in a CSS file and apply it to the scene graph.

You can specify a CSS file either directly in the FXML file or in the main program. To specify a CSS file in the main program, add a call to scene.getStylesheets(), as shown in Listing 3.5.

Listing 3.5 Adding a CSS Style Sheet in the Main Program

package myrectanglefxapp;

import javafx.application.Application;

import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class MyRectangleFXApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource(
               "MyRectangleFX.fxml"));
        Scene scene = new Scene(root, Color.LIGHTBLUE);
        scene.getStylesheets().add("myrectanglefxapp/MyCSS.css");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

It’s also possible to specify the style sheet in FXML, as shown in Listing 3.6. Note that you must include java.net.* to define element URL.

Listing 3.6 MyRectangleFX.fxml—Adding a Style Sheet

<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.effect.*?>

<StackPane id="StackPane" fx:id="stackpane" prefHeight="200" prefWidth="400"
            xmlns:fx="http://javafx.com/fxml"
            fx:controller="myrectanglefxapp.MyRectangleFXController">
     <stylesheets>
        <URL value="@MyCSS.css" />
    </stylesheets>
    <children>
        <Rectangle id="myrectangle" fx:id="rectangle" width="200" height="100"
                   arcWidth="30" arcHeight="30"
                   onMouseClicked="#handleMouseClick" />

        <Text text="My Rectangle">
            <effect>
                <Reflection />
            </effect>
            <font>
                <Font name="Verdana Bold" size="18.0" />
            </font>
        </Text>
    </children>
</StackPane>

Before we show you the MyCSS.css file, take a look at the Rectangle element in Listing 3.6. It’s much shorter now since the FXML no longer includes the style or effect property values. The FXML does, however, contain a property id value. This id attribute identifies the node for the CSS style definition.

We’ve also defined an event handler for a mouse clicked event in the Rectangle FXML (#handleMouseClick). The onMouseClicked attribute lets you wire an event handler with an FXML component. The mouse clicked event handler is invoked when the user clicks inside the Rectangle. (We’ll show you the updated controller class in the next section.)

Finally, as shown in Listing 3.6, we modified the StackPane to include element fx:id="stackpane" so we can refer to the StackPane in the controller code.

Listing 3.7 shows the CSS file MyCSS.css, which defines a style specifically for the component with id “myrectangle.”

Listing 3.7 MyCSS.css

#myrectangle {
   -fx-fill:
        linear-gradient(#ffd65b, #e68400),
        linear-gradient(#ffef84, #f2ba44),
        linear-gradient(#ffea6a, #efaa22),
        linear-gradient(#ffe657 0%, #f8c202 50%, #eea10b 100%),
        linear-gradient(from 0% 0% to 15% 50%, rgba(255,255,255,0.9),
         rgba(255,255,255,0));
   -fx-effect: dropshadow( three-pass-box, gray , 10 , 0 , 5.0 , 5.0 );
}

Animation

You don’t actually think we’d introduce JavaFX and not show some animation, do you? As it turns out, animation with JavaFX is easy when you use the high-level animation APIs called transitions.

For our example, let’s rotate the Rectangle node 180 degrees (and back to 0) twice. The animation begins when the user clicks inside the rectangle. Figure 3.13 shows the rectangle during the transition (on the right). We rotate both the Rectangle and the Text.

Figure 3.13

Figure 3.13 The Rectangle node rotates with a rotation animation

Each JavaFX Transition type controls one or more Node (or Shape) properties, as listed in Table 3.1. The RotateTransition controls a node’s rotate property. The FadeTransition controls a node’s opacity property. The TranslateTransition controls a node’s translateX and translateY properties (and translateZ if you’re working in 3D). Other transitions include PathTransition (animates a node along a Path), FillTransition (animates a shape’s fill property), StrokeTransition (animates a shape’s stroke property), and ScaleTransition (grows or shrinks a node over time).

TABLE 3.1 JavaFX Transitions

Transition

Affected Property(ies)

Applies to

RotateTransition

rotate (0 to 360)

Node

FadeTransition

opacity (0 to 1)

Node

TranslateTransition

translateX, translateY, translateZ

Node

ScaleTransition

scaleX, scaleY, scaleZ

Node

PathTransition

translateX, translateY, rotate

Node

FillTransition

fill (color)

Shape

StrokeTransition

stroke (color)

Shape

You can play multiple transitions in parallel (ParallelTransition) or sequentially (SequentialTransition). It’s also possible to control timing between two sequential transitions with a pause (PauseTransition), configure a delay before a transition begins (with Transition method setDelay()), or define an action at the completion of a Transition (with Transition action event handler property onFinished).

You start a transition with method play() or playFromStart(). Method play() initiates a transition at its current time; method playFromStart() starts the transition at time 0. Other methods include stop() and pause(). You can query a transition’s status with getStatus(), which returns one of the Animation.Status enum values RUNNING, PAUSED, or STOPPED.

Since transitions are specialized, you configure each one slightly differently. However, all transitions support the common properties duration, autoReverse, cycleCount, onFinished, currentTime, and either node or shape (for Shape-specific transitions FillTransition and StrokeTransition).

Listing 3.8 shows the modifications to the controller class to implement the RotateTransition and mouse click event handler. We instantiate the RotateTransition rt inside method initialize(). In order to rotate both the Rectangle and the Text together, we specify a rotation for the parent StackPane node, which then rotates its children together (the Rectangle and the Text). Then, inside the event handler we initiate the animation with method play().

The @FXML annotation applies to variables stackpane and rectangle, as well as method handleMouseClick(), in order to correctly wire these objects to the FXML markup.

Listing 3.8 MyRectangleFXController.java—RotateTransition

package myrectanglefxapp;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;

public class MyRectangleFXController implements Initializable {

    private RotateTransition rt;

    @FXML
    private Rectangle rectangle;
    @FXML
    private StackPane stackpane;

    @FXML
    private void handleMouseClick(MouseEvent evt) {
        rt.play();
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        rectangle.setStrokeWidth(5.0);
        rectangle.setStroke(Color.GOLDENROD);
        // Create and configure RotateTransition rt
        rt = new RotateTransition(Duration.millis(3000), stackpane);
        rt.setToAngle(180);
        rt.setFromAngle(0);
        rt.setAutoReverse(true);
        rt.setCycleCount(4);
    }
}

The RotateTransition lets you specify either a “to” angle or “by” angle value. If you omit a starting position (property fromAngle), the rotation uses the node’s current rotation property value as the starting rotation angle. Here we set autoReverse to true, which makes the StackPane rotate from angle 0 to 180 and then back again. We set cycle count to four to repeat the back and forth animation twice (back and forth counts as two cycles).

  • + Share This
  • 🔖 Save To Your Account