Nigel Eke - Personal Site

Binding the size of a list to another property.

I have a requirement to bind the size of a list to a label on the UI.  When an item gets added to the list, the label showing a count of the items in the list is to be updated.


In the following application, clicking on the Add item! button should add an item to the list and update the count of the number of items.  Currently it does the first of these tasks, but not the latter.  RT-23282 ( "sizeProperty defect report" (dead link)) has been raised to determine why that might be.  In the meantime - here's the code:


package sizepropertytest;

import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;

public class SampleController implements Initializable {

  private void handleButtonAction(ActionEvent event) {
    listProperty.add("Item#: " + (listProperty.size()+ 1));

  public void initialize(URL url, ResourceBundle rb) {
    listProperty.sizeProperty().addListener(new ChangeListener<Number>() {
      public void changed(ObservableValue<? extends Number> observedValue, Number oldValue, Number newValue) {
        System.out.println("Not fired, but should have been?");



  @FXML private Label label;
  @FXML private ListView<String> listView;

  private SimpleListProperty<String> listProperty = new SimpleListProperty(FXCollections.<String>observableArrayList());


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

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

<AnchorPane id="AnchorPane" prefHeight="123.0" prefWidth="320.0" xmlns:fx="" fx:controller="sizepropertytest.SampleController">
    <Button layoutX="14.0" layoutY="14.0" onAction="#handleButtonAction" text="Add item!" />
    <Label fx:id="label" alignment="CENTER\_RIGHT" layoutX="109.0" layoutY="13.0" prefWidth="197.0" text="Label" />
    <ListView fx:id="listView" layoutX="14.0" layoutY="46.0" prefHeight="63.5" prefWidth="292.0" />

Main Application

package sizepropertytest;

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

public class SizePropertyTest extends Application {

  public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));

    Scene scene = new Scene(root);


  public static void main(String\[\] args) {

Posted: July 07, 2012