首页 > 代码库 > java.beans.PropertyChangeListener

java.beans.PropertyChangeListener

 1 import java.beans.PropertyChangeEvent; 2 import java.beans.PropertyChangeListener; 3 import java.beans.PropertyChangeSupport; 4  5 public class DemoBeans {   6    7     private String demoName;   8     private String Version;     9     PropertyChangeSupport listeners = new PropertyChangeSupport(this);  10   11     public DemoBeans() {  12         demoName = "initValue";  13         Version="v1000";14     }  15   16   17     public String getDemoName() {  18         return demoName;  19     }  20       21   22     public void setDemoName(String demoName) {  23         String oldValue = http://www.mamicode.com/this.demoName;  24         this.demoName = demoName;  25         //发布监听事件  26         firePropertyChange("demoName", oldValue, demoName);  27           28     }  29       30     public void setDemoVersion(String demoVersion) {  31         String oldVersion = this.Version;  32         this.Version = demoVersion;  33         //发布监听事件  34         firePropertyChange("demoVersion", oldVersion, demoVersion);  35           36     }  37     public void addPropertyChangeListener(PropertyChangeListener listener) {  38         listeners.addPropertyChangeListener(listener);  39     }  40       41     public void removePropertyChangeListener(PropertyChangeListener listener){  42         listeners.addPropertyChangeListener(listener);  43     }  44       45   46     /** 47      * 触发属性改变的事件 48      */  49     protected void firePropertyChange(String prop, Object oldValue, Object newValue) {  50         listeners.firePropertyChange(prop, oldValue, newValue);  51     }  52     public static void main(String[] args) {  53         DemoBeans beans = new DemoBeans();  54         55         beans.addPropertyChangeListener(56                 new PropertyChangeListener(){  57             public void propertyChange(PropertyChangeEvent evt) {  58                  if(evt.getPropertyName().equals("demoVersion")){59                      System.out.println("version_OldValue:"+evt.getOldValue());  60                      System.out.println("version_NewValue:"+evt.getNewValue());  61                      System.out.println("version_tPropertyName:"+evt.getPropertyName());62                  }63                  else64                  {65                      System.out.println("name_OldValue:"+evt.getOldValue());  66                      System.out.println("name_NewValue:"+evt.getNewValue());  67                      System.out.println("name_tPropertyName:"+evt.getPropertyName());68                  }69                   70             }});  71 72         73         beans.setDemoName("test");  74         beans.setDemoVersion("v2000");75       76     }   77 }  

 

java.beans.PropertyChangeListener