欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解java中的PropertyChangeSupport与PropertyChangeListener

程序员文章站 2024-03-31 14:50:46
详解java中的propertychangesupport与propertychangelistener java中的propertychangesupport与prop...

详解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()); 
       
    } 
  } 
} 

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