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

java中的PropertyChangeSupport与PropertyChangeListener

程序员文章站 2022-03-01 23:14:09
...

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