编程语言

img fantasyCoder

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

发表于2004/11/2 0:26:00  1213人阅读

分类: skill

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

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.*包含了大多空包,这些方法都需要自己扩展,我们完全不需要用它定义的方法名

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

阅读全文
0 0

相关文章推荐

img
取 消
img