详解java中的PropertyChangeSupport与PropertyChangeListener
详解java中的PropertyChangeSupport与PropertyChangeListener
java中的PropertyChangeSupport与PropertyChangeListener配合使用能够实现,绑定属性会在属性值发生变化时,通知所有相关的监听器。
javaBean:
packagecom.wang.test.property; importjava.beans.PropertyChangeListener; importjava.beans.PropertyChangeSupport; publicclassTestBean{ protectedfinalPropertyChangeSupportsupport=newPropertyChangeSupport(this); privateStringstr; publicStringgetStr(){ returnstr; } publicvoidsetStr(Stringstr){ support.firePropertyChange("str",this.str,str); this.str=str; } publicvoidaddPropertyChangeListener(PropertyChangeListenerlistener){ support.addPropertyChangeListener(listener); } publicvoidremovePropertyChangeListener(PropertyChangeListenerlistener){ support.removePropertyChangeListener(listener); } }
client:
packagecom.wang.test.property; importjava.beans.PropertyChangeEvent; importjava.beans.PropertyChangeListener; publicclassPropertyChangeSupportTest{ publicstaticvoidmain(String[]args){ TestBeantest=newTestBean(); test.setStr("ddddd"); test.addPropertyChangeListener(newPropertyChangeListener1()); test.setStr("yyyy"); //test.addPropertyChangeListener(newPropertyChangeListener2()); //test.setStr("hhhhhhf"); } publicstaticclassPropertyChangeListener1implementsPropertyChangeListener{ @Override publicvoidpropertyChange(PropertyChangeEventevt){ System.out.println("1:"+evt.getPropertyName()+""+evt.getNewValue()+""+evt.getOldValue()); } } publicstaticclassPropertyChangeListener2implementsPropertyChangeListener{ @Override publicvoidpropertyChange(PropertyChangeEventevt){ System.out.println("2:"+evt.getPropertyName()+""+evt.getNewValue()+""+evt.getOldValue()); } } }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!