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

来源:互联网 发布:土地建设数据库 编辑:程序博客网 时间:2024/05/24 06:33
首先,定义一个基类,负责加入监听者,

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.*包含了大多空包,这些方法都需要自己扩展,我们完全不需要用它定义的方法名。
上面的例子完全可以用自己的方法来实现.



通过这个例子,可以方便的构建一个GUI的事件监听类。业务处理层只需要处理数据,而GUI监听器负责将数据更新到界面上。
原创粉丝点击