Home > Articles > Web Development

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

3.3 JavaFX Properties

The previous sections make frequent references to JavaFX properties. We said that JavaFX properties are similar to JavaBean properties, but JavaFX properties are much more powerful. Clearly, JavaFX properties have considerable significance in JavaFX applications. In fact, JavaFX properties are perhaps the most significant feature in JavaFX. In this section, we’ll explore JavaFX properties in detail and show you how to use them.

What Is a JavaFX Property?

At the heart of JavaFX is its scene graph, a structure that includes (perhaps many) nodes. The JavaFX rendering engine displays these nodes and ultimately what you see depends on the properties of these nodes.

Properties are oh-so-important. They make a Circle red or a Rectangle 200 pixels wide. They determine the gradient for a fill color or whether or not a text node includes reflection or a drop shadow effect. You manipulate nodes with layout controls—which are themselves nodes—by setting properties such as spacing or alignment. When your application includes animation, JavaFX updates a node’s properties over time—perhaps a node’s position, its rotation, or its opacity. In the previous sections, you’ve seen how our example applications are affected by the properties that the code manipulates.

The previous chapter describes how JavaBean properties support encapsulation and a well-defined naming convention. You can create read-write properties, read-only properties, and immutable properties. We also show how to create bound properties—properties that fire property change events to registered listeners. Let’s learn how these concepts apply to JavaFX properties.

JavaFX properties support the same naming conventions as JavaBeans properties. For example, the radius of a Circle (a JavaFX Shape) is determined by its radius property. Here, we manipulate the radius property with setters and getters.

            Circle circle1 = new Circle(10.5);
            System.out.println("Circle1 radius = " + circle1.getRadius());
            circle1.setRadius(20.5);
            System.out.println("Circle1 radius = " + circle1.getRadius());

This displays the following output.

            Circle1 radius = 10.5
            Circle1 radius = 20.5

You access a JavaFX property with property getter method. A property getter consists of the property name followed by the word “Property.” Thus, to access the JavaFX radius property for circle1 we use the radiusProperty() method. Here, we print the radius property

      System.out.println(circle1.radiusProperty());

which displays

      DoubleProperty [bean: Circle[centerX=0.0, centerY=0.0, radius=20.5,
            fill=0x000000ff], name: radius, value: 20.5]

Typically, each JavaFX property holds metadata, including its value, the property name, and the bean that contains it. We can access this metadata individually with property methods getValue(), getName(), and getBean(), as shown in Listing 3.9. You can also access a property’s value with get().

Listing 3.9 Accessing JavaFX Property Metadata

            System.out.println("circle1 radius property value: "
                  + circle1.radiusProperty().getValue());
            System.out.println("circle1 radius property name: "
                  + circle1.radiusProperty().getName());
            System.out.println("circle1 radius property bean: "
                  + circle1.radiusProperty().getBean());
            System.out.println("circle1 radius property value: "
                  + circle1.radiusProperty().get());
            Output:
            circle1 radius property value: 20.5
            circle1 radius property name: radius
            circle1 radius property bean: Circle@243e0b62
            circle1 radius property value: 20.5

Using Listeners with Observable Properties

All JavaFX properties are Observable. This means that when a property’s value becomes invalid or changes, the property notifies its registered InvalidationListeners or ChangeListeners. (There are differences between invalidation and change, which we’ll discuss shortly.) You register listeners directly with a JavaFX property. Let’s show you how this works by registering an InvalidationListener with a Circle’s radius property. Since our example does not build a scene graph, we’ll create a plain Java application (called MyInvalidationListener) using these steps.

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

    Figure 3.14

    Figure 3.14 Create a Java Application when you don’t need a JavaFX scene graph

  2. NetBeans displays the Name and Location dialog. Provide MyInvalidationListener for the Project Name, and click Browse to select the desired location, as shown in Figure 3.15. Click Finish.

    Figure 3.15

    Figure 3.15 Specify the project’s name and location

Using InvalidationListeners

Listing 3.10 creates two Circle objects and registers an InvalidationListener with the radius property of circle2. Inside the event handler, the invalidated() method sets the radius property of circle1 with circle2’s new value. Essentially, we are saying “make sure the radius property of circle1 is always the same as the radius property of circle2.”

A registered InvalidationListener is notified when the current value is no longer valid.4 Invalidation events supply the observable value, which is the JavaFX property including the metadata. If you don’t need to access the previous value, listening for invalidation events instead of change events (discussed next) can be more efficient.

Listing 3.10 Registering a JavaFX InvalidationListener

package myinvalidationlistener;

import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.scene.shape.Circle;

public class MyInvalidationListener {

    public static void main(String[] args) {

        // Define some circles
        final Circle circle1 = new Circle(10.5);
        final Circle circle2 = new Circle(15.5);

        // Add an invalidation listener to circle2's radius property
        circle2.radiusProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable o) {
                System.out.println("Invalidation detected for " + o);
                circle1.setRadius(circle2.getRadius());
            }
        });

        System.out.println("Circle1: " + circle1.getRadius());
        System.out.println("Circle2: " + circle2.getRadius());
        circle2.setRadius(20.5);
        System.out.println("Circle1: " + circle1.getRadius());
        System.out.println("Circle2: " + circle2.getRadius());
    }

}
Output:
Circle1: 10.5
Circle2: 15.5
Invalidation detected for DoubleProperty [bean: Circle[centerX=0.0,
centerY=0.0, radius=20.5, fill=0x000000ff], name: radius, value: 20.5]
Circle1: 20.5
Circle2: 20.5

The output shows the original radius values for both Circles (10.5 and 15.5), the invalidation event handler output, and the updated radius property for both Circles. The getRadius() method displays the value of the radius property. You can also use radiusProperty().get() or radiusProperty().getValue(), but the traditionally named getRadius() is more familiar and more efficient.

Note that with InvalidationListeners, you must cast the non-generic Observable o to ObservableValue<Number> to access the new value in the event handler.

      System.out.println("new value = " +
               ((ObservableValue<Number>) o).getValue().doubleValue());

Using ChangeListeners

Listing 3.11 shows the same program with a ChangeListener instead of an InvalidationListener attached to circle2’s radius property (project MyChangeListener). ChangeListener is generic and you override the changed() method.

The event handler’s signature includes the generic observable value (ov), the observable value’s old value (oldValue), and the observable value’s new value (newValue). The new and old values are the property values (here, Number objects) without the JavaFX property metadata. Inside the changed() method, we set circle1’s radius property with the setRadius(newValue.doubleValue()) method. Because ChangeListeners are generic, you can access the event handler parameters without type casts.

Listing 3.11 Registering a JavaFX Property ChangeListener

package mychangelistener;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.shape.Circle;
public class MyChangeListener  {

    public static void main(String[] args) {

        // Define some circles
        final Circle circle1 = new Circle(10.5);
        final Circle circle2 = new Circle(15.5);

        // Use change listener to track changes to circle2's radius property
      circle2.radiusProperty().addListener(new ChangeListener<Number>() {

            @Override
            public void changed(ObservableValue<? extends Number> ov,
                            Number oldValue, Number newValue) {
                System.out.println("Change detected for " + ov);
                circle1.setRadius(newValue.doubleValue());
            }
        });

        System.out.println("Circle1: " + circle1.getRadius());
        System.out.println("Circle2: " + circle2.getRadius());
        circle2.setRadius(20.5);
        System.out.println("Circle1: " + circle1.getRadius());
        System.out.println("Circle2: " + circle2.getRadius());
    }

}
Output:
Circle1: 10.5
Circle2: 15.5
Change detected for DoubleProperty [bean: Circle[centerX=0.0, centerY=0.0,
radius=20.5, fill=0x000000ff], name: radius, value: 20.5]
Circle1: 20.5
Circle2: 20.5

The output of the MyChangeListener program is similar to the InvalidationListener output in Listing 3.10.5 Note that ChangeListeners make it possible to access the old value of a changed property and generics mean casting is not needed.

Read-Only Properties

JavaFX also supports read-only properties. Although you cannot modify read-only properties directly with setters, the value of a read-only property can change. A typical use of a read-only property is with a bean that maintains a property’s value internally. For example, the currentTime property of an Animation object (a Transition or a Timeline) is read only. You can read its value with getCurrentTime() and access the property with currentTimeProperty(), but you can’t update its value with a setter.

Since read-only properties change and are observable, you can listen for change and invalidation events, just as you can with read-write properties. You can also use read-only (as well as read-write) JavaFX properties in binding expressions, which we discuss next.

Binding

There may be situations where you need to define a ChangeListener and register it with an object’s property to monitor its old and new values. However, in many cases, the reason you’d like to track property changes is to update another object with a new value (as we did in Listing 3.10 on page 106 and Listing 3.11 on page 108).

A JavaFX feature called binding addresses this use case. Because JavaFX properties are observable, they can participate in binding expressions. Binding means that you specify a JavaFX property as dependent on another JavaFX property’s value. Binding expressions can be simple, or they can involve many properties in a cascade of property updates initiated perhaps by just one property changing its value (a program’s butterfly effect). Binding is a powerful feature in JavaFX that lets you succinctly express dependencies among object properties in applications without defining or registering listeners. Let’s look at some examples.

Unidirectional Binding

To bind one JavaFX property to another, use method bind() with a JavaFX property.

            circle1.radiusProperty().bind(circle2.radiusProperty());

This binding expression states that circle1’s radius property will always have the same value as circle2’s radius property. We say that circle1’s radius property is dependent on circle2’s radius property. This binding is one way; only circle1’s radius property updates when circle2’s radius property changes and not vice versa.

Binding expressions include an implicit assignment. That is, when we bind the circle1 radius property to circle2’s radius property, the update to circle1’s radius property occurs when the bind() method is invoked.

When you bind a property, you cannot change that property’s value with a setter.

            circle1.setRadius(someValue);         // can’t do this

There are some restrictions with binding. Attempting to define a circular binding results in a stack overflow. Attempting to set a bound property results in a runtime exception.

            java.lang.RuntimeException: A bound value cannot be set.

Let’s show you an example program with binding now. Listing 3.12 defines two Circle objects, circle1 and circle2. This time, instead of an InvalidationListener or ChangeListener that tracks changes to circle2 and then updates circle1, we bind circle1’s radius property to circle2’s radius property.

Listing 3.12 Unidirectional Bind—MyBind.java

package asgteach.bindings;

import javafx.scene.shape.Circle;

public class MyBind {

    public static void main(String[] args) {
        Circle circle1 = new Circle(10.5);
        Circle circle2 = new Circle(15.5);
        System.out.println("Circle1: " + circle1.getRadius());
        System.out.println("Circle2: " + circle2.getRadius());
        // Bind circle1 radius to circle2 radius
        circle1.radiusProperty().bind(circle2.radiusProperty());
        if (circle1.radiusProperty().isBound()) {
            System.out.println("Circle1 radiusProperty is bound");
        }

        // Radius properties are now the same
        System.out.println("Circle1: " + circle1.getRadius());
        System.out.println("Circle2: " + circle2.getRadius());

        // Both radius properties will now update
        circle2.setRadius(20.5);
        System.out.println("Circle1: " + circle1.getRadius());
        System.out.println("Circle2: " + circle2.getRadius());

        // circle1 radius no longer bound to circle2 radius
        circle1.radiusProperty().unbind();
        if (!circle1.radiusProperty().isBound()) {
            System.out.println("Circle1 radiusProperty is unbound");
        }

        // Radius properties are now no longer the same
        circle2.setRadius(30.5);
        System.out.println("Circle1: " + circle1.getRadius());
        System.out.println("Circle2: " + circle2.getRadius());
    }

}
Output:
Circle1: 10.5
Circle2: 15.5
Circle1 radiusProperty is bound
Circle1: 15.5
Circle2: 15.5
Circle1: 20.5
Circle2: 20.5
Circle1 radiusProperty is unbound
Circle1: 20.5
Circle2: 30.5

In this example, the Circle objects are initialized with different values, which are displayed. We then bind circle1’s radius property to circle2’s radius property and display the radius values again. With the bind’s implicit assignment, the circle radius values are now the same (15.5). When the setter changes circle2’s radius to 20.5, circle1’s radius updates.

The isBound() method checks if a JavaFX property is bound and the unbind() method removes the binding on a JavaFX property. Note that after unbinding circle1’s radius property, updating circle2’s radius no longer affects the radius for circle1.

Bidirectional Binding

Bidirectional binding lets you specify a binding with two JavaFX properties that update in both directions. Whenever either property changes, the other property updates. Note that setters for both properties always work with bidirectional binding (after all, you have to update the values somehow).

Bidirectional binding is particularly suited for keeping UI view components synchronized with model data. If the model changes, the view automatically refreshes. And if the user inputs new data in a form, the model updates.

Listing 3.13 shows how to use JavaFX property method bindBidirectional(). After objects circle1 and circle2 have their radius properties bound, both properties acquire value 15.5 (circle2’s radius property value), and a change to either one updates the other. Note that setters update the radius property values.

You can also unbind the properties with method unbindBidirectional().

Listing 3.13 Bidirectional Binding—MyBindBidirectional.java

package asgteach.bindings;
import javafx.scene.shape.Circle;

public class MyBindBidirectional {

    public static void main(String[] args) {
        Circle circle1 = new Circle(10.5);
        Circle circle2 = new Circle(15.5);

        // circle1 takes on value of circle2 radius
        circle1.radiusProperty().bindBidirectional(circle2.radiusProperty());
        System.out.println("Circle1: " + circle1.getRadius());
        System.out.println("Circle2: " + circle2.getRadius());

        circle2.setRadius(20.5);
        // Both circles are now 20.5
        System.out.println("Circle1: " + circle1.getRadius());
        System.out.println("Circle2: " + circle2.getRadius());

        circle1.setRadius(30.5);
        // Both circles are now 30.5
        System.out.println("Circle1: " + circle1.getRadius());

        System.out.println("Circle2: " + circle2.getRadius());

        circle1.radiusProperty().unbindBidirectional(circle2.radiusProperty());
    }

}
Output:
Circle1: 15.5
Circle2: 15.5
Circle1: 20.5
Circle2: 20.5
Circle1: 30.5
Circle2: 30.5

Fluent API and Bindings API

Method bind() works well with JavaFX properties that are the same type. You bind one property to a second property. When the second property changes, the first one’s value gets updated automatically.

However, in many cases, a property’s value will be dependent on another property that you have to manipulate in some way. Or, a property’s value may need to update when more than one property changes. JavaFX has a Fluent API that helps you construct binding expressions for these more complicated relationships.

The Fluent API includes methods for common arithmetic operations, such as add(), subtract(), divide(), and multiply(), boolean expressions, negate(), and conversion to String with asString(). You can use these Fluent API methods with binding expressions. Their arguments are other properties or non-JavaFX property values.

Here’s an example that displays a temperature in both Celsius and Fahrenheit using the conversion formula in a binding expression for the Fahrenheit label.

            // Suppose you had a "temperature" object
            Temperature myTemperature = new Temperature(0);

            // Create two labels
            Label labelF = new Label();
            Label labelC = new Label();

            // Bind the labelC textProperty to the Temperature celsiusProperty
            labelC.textProperty().bind(myTemperature.celsiusProperty().asString()
                      .concat(" C"));

            // Bind the labelF textProperty to the Temperature celsiusProperty
            // using F = 9/5 C + 32
            labelF.textProperty().bind(myTemperature.celsiusProperty().multiply(9)
                      .divide(5).add(32)
                      .asString().concat(" F"));

Another common use for binding is enabling and disabling a control based on some condition. Here we bind the disable property of a button based on the status of an animation. If the animation is running, the button is disabled.

            // Bind button's disableProperty to myTransition running or not
            startButton.disableProperty().bind(myTransition.statusProperty()
                      .isEqualTo(Animation.Status.RUNNING));

The Bindings API offers additional flexibility in building binding expressions. The Bindings class has static methods that let you manipulate observable values. For example, here’s how to implement the Fahrenheit temperature conversion using the Bindings API.

         labelF.textProperty().bind(
                Bindings.format(" %1.1f F",
                Bindings.add(
                Bindings.divide(
                Bindings.multiply(9, myTemperature.celsiusProperty()),
                     5), 32)));

Because the Bindings API requires that you build your expression “inside-out,” the expression may not be as readable as the Fluent API. However, the Bindings methods are useful, particularly for formatting the result of binding expressions. The above Bindings.format() gives you the same flexibility as java.util.Formatter for creating a format String. You can also combine the Bindings API with the Fluent API.

Let’s look at another example of using the Fluent API. Figure 3.16 shows an application with a Rectangle. As you resize the window, the Rectangle grows and shrinks. The opacity of the Rectangle also changes when you resize. As the window gets larger, the rectangle gets more opaque, making it appear brighter since less of the dark background is visible through a less-transparent rectangle.

Figure 3.16

Figure 3.16 The Rectangle’s dimensions and fill color change with window resizing

Listing 3.14 shows the code for this application (project MyFluentBind). Constructors create the drop shadow, stack pane, and rectangle, and setters configure them. To provide dynamic resizing of the rectangle, we bind the rectangle’s width property to the scene’s width property divided by two. Similarly, we bind the rectangle’s height property to the scene’s height property divided by two. (Dividing by two keeps the rectangle centered in the window.)

The rectangle’s opacity is a bit trickier. The opacity property is a double between 0 and 1, with 1 being fully opaque and 0 being completely transparent (invisible). So we rather arbitrarily add the scene’s height and width together and divide by 1000 to keep the opacity within the target range of 0 and 1. This makes the opacity change as the rectangle resizes.

Listing 3.14 Fluent API—MyFluentBind.java

package asgteach.bindings;
import javafx.application.Application;
import javafx.geometry.Pos;
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.stage.Stage;

public class MyFluentBind extends Application {

    @Override
    public void start(Stage stage) {

        DropShadow dropShadow = new DropShadow(10.0,
                           Color.rgb(150, 50, 50, .688));
        dropShadow.setOffsetX(4);
        dropShadow.setOffsetY(6);

        StackPane stackPane = new StackPane();
        stackPane.setAlignment(Pos.CENTER);
        stackPane.setEffect(dropShadow);

        Rectangle rectangle = new Rectangle(100, 50, Color.LEMONCHIFFON);
        rectangle.setArcWidth(30);
        rectangle.setArcHeight(30);

        stackPane.getChildren().add(rectangle);

        Scene scene = new Scene(stackPane, 400, 200, Color.LIGHTSKYBLUE);
        stage.setTitle("Fluent Binding");

        rectangle.widthProperty().bind(scene.widthProperty().divide(2));
        rectangle.heightProperty().bind(scene.heightProperty().divide(2));

        rectangle.opacityProperty().bind(
              scene.widthProperty().add(scene.heightProperty())
                        .divide(1000));

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

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

Custom Binding

When the Fluent API or Bindings API does not apply to your application, you can create a custom binding object. With custom binding, you specify two items:

  • the JavaFX property dependencies
  • how to compute the desired value.

Let’s rewrite the previous example and create a custom binding object.

First, here is the binding expression presented earlier for the rectangle’s opacity property.

        rectangle.opacityProperty().bind(
              scene.widthProperty().add(scene.heightProperty())
                        .divide(1000));

The binding has two JavaFX property dependencies: the scene’s width and height properties.

Next, determine how to compute the value with this binding expression. Without using the Fluent API or the Bindings API, the computation (which results in a double value) is

            double myComputedValue = (scene.getWidth() + scene.getHeight()) / 1000;

That is, the opacity’s value is a double that is the sum of the scene’s width and height divided by 1000.

For this example, the custom binding object is type DoubleBinding. You specify the JavaFX property dependencies as arguments in the binding object’s anonymous constructor using super.bind(). The overridden computeValue() method returns the desired value (here, a double). The computeValue() method is invoked whenever any of the properties listed as dependencies change. Here’s what our custom binding object looks like.

        DoubleBinding opacityBinding = new DoubleBinding() {
            {
                // Specify the dependencies with super.bind()
                super.bind(scene.widthProperty(), scene.heightProperty());
            }
            @Override
            protected double computeValue() {
                // Return the computed value
                return (scene.getWidth() + scene.getHeight()) / 1000;
            }
        };

For StringBinding, computeValue() returns a String. For IntegerBinding, computeValue() returns an integer, and so forth.

To specify this custom binding object with the Rectangle’s opacity property, use

            rectangle.opacityProperty().bind(opacityBinding);

Now let’s show you another custom binding example. Figure 3.17 shows a similar JavaFX application with a rectangle whose size and opacity change as the window resizes. This time, we make sure that the opacity is never greater than 1.0 and we display the opacity in a text node inside the rectangle. The text is formatted and includes “opacity = ” in front of the value.

Figure 3.17

Figure 3.17 The Rectangle displays its changing opacity value in a Text component

Listing 3.15 shows the code for this program (project MyCustomBind). The same code creates the drop shadow, rectangle, and stack pane as in the previous example. The rectangle’s height and width properties use the same Fluent API binding expression. Now method computeValue() returns a double for the opacity and makes sure its value isn’t greater than 1.0.

The text label’s text property combines the custom binding object opacityBinding with method Bindings.format() to provide the desired formatting of the text.

Listing 3.15 Custom Binding Example—MyCustomBind.java

public class MyCustomBind extends Application {

    @Override
    public void start(Stage stage) {

        . . . code omitted to build the Rectangle, StackPane
               and DropShadow . . .

        Text text = new Text();
        text.setFont(Font.font("Tahoma", FontWeight.BOLD, 18));

        stackPane.getChildren().addAll(rectangle, text);

        final Scene scene = new Scene(stackPane, 400, 200, Color.LIGHTSKYBLUE);
        stage.setTitle("Custom Binding");

        rectangle.widthProperty().bind(scene.widthProperty().divide(2));
        rectangle.heightProperty().bind(scene.heightProperty().divide(2));

        DoubleBinding opacityBinding = new DoubleBinding() {
            {
                // List the dependencies with super.bind()
                super.bind(scene.widthProperty(), scene.heightProperty());
            }
            @Override
            protected double computeValue() {
               // Return the computed value
               double opacity = (scene.getWidth() + scene.getHeight()) / 1000;
               return (opacity > 1.0) ? 1.0 : opacity;
            }
        };
        rectangle.opacityProperty().bind(opacityBinding);
        text.textProperty().bind((Bindings.format(
                           "opacity = %.2f", opacityBinding)));

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

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

How do you create binding objects that return compute values that are not one of the standard types? In this situation, use ObjectBinding with generics. For example, Listing 3.16 shows a custom binding definition that returns a darker Color based on the fill property of a Rectangle. The binding object is type ObjectBinding<Color> and the computeValue() return type is Color. (The cast here is necessary because a Shape’s fill property is a Paint object, which can be a Color, ImagePattern, LinearGradient, or RadialGradient.)

Listing 3.16 ObjectBinding with Generics

        ObjectBinding<Color> colorBinding = new ObjectBinding<Color>() {
            {
                super.bind(rectangle.fillProperty());
            }

            @Override
            protected Color computeValue() {
                if (rectangle.getFill() instanceof Color) {
                    return ((Color)rectangle.getFill()).darker();
                } else {
                    return Color.GRAY;
                }
            }
        };
  • + Share This
  • 🔖 Save To Your Account