微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

详解java中的PropertyChangeSupport与PropertyChangeListener

详解java中的PropertyChangeSupport与Propertychangelistener

java中的PropertyChangeSupport与Propertychangelistener配合使用能够实现,绑定属性会在属性值发生变化时,通知所有相关的监听器。

javaBean:

package com.wang.test.property; 
 
import java.beans.Propertychangelistener; 
import java.beans.PropertyChangeSupport; 
 
public class TestBean { 
 
  protected final PropertyChangeSupport support = new PropertyChangeSupport(this); 
   
  private String str; 
   
  public String getstr() { 
    return str; 
  } 
 
  public void setStr(String str) { 
    support.firePropertyChange("str",this.str,str); 
    this.str = str; 
  } 
   
  public void addPropertychangelistener(Propertychangelistener listener) { 
    support.addPropertychangelistener(listener); 
  } 
   
  public void removePropertychangelistener(Propertychangelistener listener) { 
    support.removePropertychangelistener(listener); 
  } 
} 

 client:

package com.wang.test.property; 
 
import java.beans.PropertyChangeEvent; 
import java.beans.Propertychangelistener; 
 
public class PropertyChangeSupportTest { 
 
  public static void main(String[] args) {  
     
    TestBean test = new TestBean(); 
    test.setStr("ddddd"); 
    test.addPropertychangelistener(new Propertychangelistener1()); 
    test.setStr("yyyy"); 
     
    //test.addPropertychangelistener(new Propertychangelistener2()); 
    //test.setStr("hhhhhhf"); 
  }  
    
  public static class Propertychangelistener1 implements Propertychangelistener{ 
 
    @Override 
    public void propertyChange(PropertyChangeEvent evt) { 
      System.out.println( "1: " + evt.getPropertyName() + "  " + evt.getNewValue() + "  " + evt.getoldValue()); 
       
    } 
  } 
   
  public static class Propertychangelistener2 implements Propertychangelistener{ 
 
    @Override 
    public void propertyChange(PropertyChangeEvent evt) { 
      System.out.println( "2: " + evt.getPropertyName() + "  " + evt.getNewValue() + "  " + evt.getoldValue()); 
       
    } 
  } 
} 

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐