java.beans.PropertyChangeSupport小解! 简洁精辟
来源:互联网 发布:elisa试剂盒数据 编辑:程序博客网 时间:2024/04/28 18:49
简要介绍一下,java.beans.PropertyChangeSupport是一个实用工具类,支持绑定该属性的bean能够使用该类。还是不多废话了,用代码说话。
import java.beans.PropertyChangeListener;import java.beans.PropertyChangeSupport;public class PropertyChangeSupportTest {transient protected PropertyChangeSupport listeners = new PropertyChangeSupport(this);public void addPropertyChangeListener(PropertyChangeListener listener) {listeners.addPropertyChangeListener(listener);}protected void firePropertyChange(String prop, Object old, Object newValue) {listeners.firePropertyChange(prop, old, newValue);}public void removePropertyChangeListener(PropertyChangeListener l) {listeners.removePropertyChangeListener(l);}}
可以看见PropertyChangeSupport的构造方法,是将此类本身绑定到该属性,以便他的子类也能够使用此工具类。主要看他的第2个方法,触发属性变化事件(prop为绑定的属性名,在后面的事件处理中可以根据此属性名获得事件处理源)
再看看它的子类:
public class BeanTest extends PropertyChangeSupportTest { public static final String TEST = "test"; private String name = ""; public void setName(String name) { if (this.name.equals(name)) { System.out.println("BeanTest 的 name 属性没有变化!"); return; } this.name = name; firePropertyChange(TEST, null, name); } public String getName() { return this.name; }}BeanTest类有一个name属性,在改变name的值时,会触发PropertyChangeEvent事件。接下来我们看看事件监听极其处理:
import java.beans.PropertyChangeEvent;import java.beans.PropertyChangeListener;public class BeanTestListener implements PropertyChangeListener{ public void propertyChange(PropertyChangeEvent evt) { if(evt.getPropertyName().equals(BeanTest.TEST)) System.out.println("BeanTest 的 name 属性变化!"); } public static void main(String[] args){ BeanTest test = new BeanTest(); test.addPropertyChangeListener(new BeanTestListener()); test.setName("hql_"); test.setName("hql_"); System.out.println(test.getName()); }}
可以看到是通过evt.getPropertyName().equals(BeanTest.TEST)来确定事件源的。运行结果如下:
BeanTest 的 name 属性变化!BeanTest 的 name 属性没有变化!hql_
/**
* 当执行setName操作时,会触发firePropertyChange事件,
* 因为PropertyChangeSupportTest和PropertyChangeSupport绑定
* 那么在BeanTestListener中,因为添加里支持类的监听器,所以应该触发propertyChange事件,
* 并且会根据evt.getPropertyName()来获得你在BeanTest中触发事件是绑定的属性名称
*/
- java.beans.PropertyChangeSupport小解! 简洁精辟
- 比较精辟的PVLAN小解
- JAVA JRE与JDK的区别(简洁,详细,精辟)
- Java 设计模式 PropertyChangeSupport
- java PropertyChangeSupport类详解
- java多态性精辟解释
- java内存分析【精辟】
- Java IO精辟详解
- java beans
- Java Beans
- Java Beans
- Java Beans
- Java Beans
- java beans
- Java Beans
- Java Beans
- Java Beans
- java 安全 加密 小解
- 新起点,新跨越,起航2013
- 计算机专业学习多年的苦恼
- Yii使用技巧汇集
- 去掉这控制台窗口
- 专家讲解 Hadoop:HBASE松散数据存储设计
- java.beans.PropertyChangeSupport小解! 简洁精辟
- android sensor
- JS 修改URL参数
- Android4.2.2系统手机连接电脑
- java利用barcode4j生成条形码
- Linux多线程,线程同步(2)
- C#中百钱百鸡的多种算法
- 从程序员到项目经理(6):程序员加油站 -- 懂电脑更要懂人脑
- [数学]-绘制三角函数