Detecting Changes in an ObservableList - Java JavaFX

Java examples for JavaFX:ObservableList

Description

Detecting Changes in an ObservableList

Demo Code

import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;

public class Main {
  public static void main(String[] args) {
    ObservableList<String> list =
      FXCollections.observableArrayList("one", "two");

    System.out.println("After creating the list: " + list);

    list.addListener(Main::onChanged);//from  w  w w.j  a  va2s .  c  o m

    list.addAll("three", "four");
    System.out.println("After addAll() - list: " + list);

    list.remove(1, 3);
    System.out.println("After remove() - list: " + list);

    list.retainAll("one");
    System.out.println("After retainAll() - list: " + list);

    list.set(0, "ONE");
    System.out.println("After set() - list: " + list);
  }

  public static void onChanged(ListChangeListener.Change<? extends String> change) {
    while (change.next()) {
      if (change.wasPermutated()) {
        System.out.println("A permutation is detected.");
      }
      else if (change.wasUpdated()) {
        System.out.println("An update is detected.");
      }
      else if (change.wasReplaced()) {
        System.out.println("A replacement is detected.");
      }
      else {
        if (change.wasRemoved()) {
          System.out.println("A removal is detected.");
        }
        else if (change.wasAdded()) {
          System.out.println("An addiiton is detected.");
        }
      }
    }
  }

}

Related Tutorials