详解java中的PropertyChangeSupport与PropertyChangeListener
java中的PropertyChangeSupport与PropertyChangeListener配合使用能够实现,绑定属性会在属性值发生变化时,通知所有相关的监听器。
javaBean:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
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()); } } } |
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://hejiawangjava.iteye.com/blog/2391916