Java Event Listener to detect a variable change

前端 未结 7 1722
逝去的感伤
逝去的感伤 2021-02-05 14:38

I cannot seem to find an answer anywhere to my question. Is there any event listener which can detect the changing of a boolean or other variable and then act on it. Or is it p

7条回答
  •  故里飘歌
    2021-02-05 15:29

    you can also try to implement an Observer.

    First create the observable object:

    import java.util.Observable;
    
    public class StringObservable extends Observable {
     private String name;
    
    
     public StringObservable(String name) {
      this.name = name;
     }
    
     public String getName() {
      return name;
     }
    
    
     public void setName(String name) {
      this.name = name;
      setChanged();
      notifyObservers(name);
     }
    
    }
    

    Then the observer:

    import java.util.Observable;
    import java.util.Observer;
    
    public class NameObserver implements Observer {
     private String name;
    
     public NameObserver() {
      name = null;
     }
    
     public void update(Observable obj, Object arg) {
      if (arg instanceof String) {
       name = (String) arg;
       System.out.println("NameObserver: Name changed to " + name);
      } else {
       System.out.println("NameObserver: Some other change to subject!");
      }
     }
    }
    

    And in your main (or wherever else):

    public class TestObservers {
     public static void main(String args[]) {
    
      // Create the Subject and Observers.
      StringObservable s = new StringObservable("Test");
      NameObserver nameObs = new NameObserver();
    
      // Add the Observer
      s.addObserver(nameObs);
    
    
      // Make changes to the Subject.
      s.setName("Test1");
      s.setName("Test2");
     }
    }
    

    Mostly found here

提交回复
热议问题