Tutorials     About     RSS
Tech and Media Labs

JavaFX Properties

Jakob Jenkov
Last update: 2020-11-23

A JavaFX Property is a special kind member variable of JavaFX controls. JavaFX properties are typically used to contain control properties such as X and Y position, width and height, text, children and other central properties of JavaFX controls. You can attach change listeners to JavaFX properties so other components can get notified when the value of the property changes, and you can bind properties to each other so when one property value changes, so does the other. In this JavaFX property tutorial I will explain how JavaFX properties work, and how to use them.

JavaFX Property Example

Here is a JavaFX GUI example showing how to access the widthProperty and prefWidthProperty of a JavaFX Pane, as well as adding a change listener to both. Notice how one of the change listeners is implemented as an anonymous Java class, and the other as a Java Lambda Expression. This is just to show you two different ways of achieving the same goal of attaching an event listener to a JavaFX property.

import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class PropertyExample extends Application {

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

  public void start(Stage primaryStage) {

    Pane pane = new Pane();

    ReadOnlyDoubleProperty widthProperty = pane.widthProperty();
    widthProperty.addListener( new ChangeListener<Number> (){
      @Override
      public void changed(
        ObservableValue<? extends Number> observableValue,
        Number oldVal, Number newVal) {

          System.out.println("widthProperty changed from "
            + oldVal.doubleValue() + " to " + newVal.doubleValue());
      }
    });


    DoubleProperty prefWidthProperty = pane.prefWidthProperty();
    prefWidthProperty.addListener(
      (ObservableValue<? extends Number> prop,
        Number oldVal, Number newVal) -> {

        System.out.println("prefWidthProperty changed from "
          + oldVal.doubleValue() + " to " + newVal.doubleValue());
    });

    prefWidthProperty.set(123);

    Scene scene = new Scene(pane, 1024, 800, true);
    primaryStage.setScene(scene);
    primaryStage.setTitle("2D Example");

    primaryStage.show();
  }
}

When the instruction prefWidthProperty.set(123); is called, the prefWidthProperty change listener will get called. Additionally, every time the UI is resized then the Pane is resized too, and the widthProperty change listener will get called.

Jakob Jenkov

Featured Videos

















Sponsored Ads

Maildroppa - Smart Email Marketing Solution
Close TOC

All Trails

Trail TOC

Page TOC

Previous

Next