JavaFX ObservableValue handle change event

Description

JavaFX ObservableValue handle change event

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ObservableValue;

public class Main {
  public static void main(String[] args) {
    // Create a counter property
    IntegerProperty counter = new SimpleIntegerProperty(100);

    // Add a change listener to the counter property
    counter.addListener(Main::changed);//from  w  w w . j  ava  2  s.co  m

    System.out.println("A");
    counter.set(101);
    System.out.println("B");

    // Try setting the same value
    System.out.println("C");
    counter.set(101); // No change event will be fired.
    System.out.println("D");

    // Try setting a different value
    System.out.println("E");
    counter.set(103);
    System.out.println("F");
  }

  public static void changed(ObservableValue<? extends Number> prop, Number oldValue, Number newValue) {
    System.out.print("Counter changed: ");
    System.out.println("Old = " + oldValue + ", new = " + newValue);
  }
}

Using inner anonymous class

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;

public class Main {
  public static void main(String[] args) {
    // Create a counter property
    IntegerProperty counter = new SimpleIntegerProperty(100);

    counter.addListener(new ChangeListener<Number>() {
      @Override//from  ww w. j a  v  a2s .  c  o  m
      public void changed(ObservableValue<? extends Number> prop, Number oldValue, Number newValue) {
        System.out.print("Counter changed: ");
        System.out.println("Old = " + oldValue + ", new = " + newValue);
      }
    });
    System.out.println("A");
    counter.set(101);
    System.out.println("B");

    // Try setting the same value
    System.out.println("C");
    counter.set(101); // No change event will be fired.
    System.out.println("D");

    // Try setting a different value
    System.out.println("E");
    counter.set(103);
    System.out.println("F");
  }

}



PreviousNext

Related