HELLOWORLD级事件属性监听小技巧,随便写了点测试代码

类别:Java 点击:0 评论:0 推荐:

首先,定义一个基类,负责加入监听者,

package net.cafe;

import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeListener;

/**
 * Created by IntelliJ IDEA.
 * User: JJYAO
 * Date: 2004-11-1
 * Time: 23:01:56
 * To change this template use File | Settings | File Templates.
 */
public class BaseEventBean  {

    protected  PropertyChangeSupport  pcs;

    public void addPropertyChangeListener(PropertyChangeListener listener){
        if(pcs == null){
            pcs = new PropertyChangeSupport(this);
        }
        pcs.addPropertyChangeListener(listener);
   }

    public void removeChangeListener(PropertyChangeListener listener) {
        if(pcs != null){
            pcs.removePropertyChangeListener(listener);
        }
    }

}

 

一个POJO继承这个类,并在SET方法里添加触发事件的方法

package net.cafe;

/**
 * Created by IntelliJ IDEA.
 * User: JJYAO
 * Date: 2004-11-1
 * Time: 23:15:34
 * To change this template use File | Settings | File Templates.
 */
public class FoolBean extends BaseEventBean {

    private String userName;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String newPassword) {
        String oldPassword =  password;
        this.password = newPassword;
        pcs.firePropertyChange("password",oldPassword,password);
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

}

 

属性监听者

package net.cafe;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;

/**
 * Created by IntelliJ IDEA.
 * User: JJYAO
 * Date: 2004-11-1
 * Time: 23:12:33
 * To change this template use File | Settings | File Templates.
 */
public class Listener  implements PropertyChangeListener  {

    public void propertyChange(PropertyChangeEvent evt) {
        System.out.println("==========old value========="  + evt.getOldValue())  ;
         System.out.println("==========new Value========" + evt.getNewValue());
    }
}

测试代码

package net.cafe;

/**
 * Created by IntelliJ IDEA.
 * User: JJYAO
 * Date: 2004-11-1
 * Time: 23:24:28
 * To change this template use File | Settings | File Templates.
 */
public class BeanEventTest {

    public static void main(String[] args){
        FoolBean bean = new FoolBean();
        bean.addPropertyChangeListener(new Listener());
        bean.setPassword("22222");
         bean.setPassword("33333");
    }
}

BTW,SUN的java.beans.*包含了大多空包,这些方法都需要自己扩展,我们完全不需要用它定义的方法名

上面的例子完全可以用自己的方法来实现,

本文地址:http://com.8s8s.com/it/it13949.htm