Java Observable.hasChanged()

Syntax

Observable.hasChanged() has the following syntax.

public boolean hasChanged()

Example

In the following code shows how to use Observable.hasChanged() method.


/*from   w  w w. ja va 2  s  .  com*/
import java.util.Observable;
import java.util.Observer;

class ObservedObject extends Observable {
   private String watchedValue;
   
   public ObservedObject(String value) {
      watchedValue = value;
   }
   
   public void setValue(String value) {
      // if value has changed notify observers
      if(!watchedValue.equals(value)) {
         watchedValue = value;
         
         // mark as value changed
         setChanged();
      }
      
   }
}
class MainObserver implements Observer {
   public void update(Observable obj, Object arg) {
      System.out.println("Update called");
   }
}

public class Main{
   public static void main(String[] args) {
      ObservedObject watched = new ObservedObject("Original Value");
      MainObserver watcher = new MainObserver();
      watched.addObserver(watcher);

      watched.setValue("New Value");
      if(watched.hasChanged())
         System.out.println("Value changed");
      else
         System.out.println("Value not changed");
   }
}

The code above generates the following result.