现在的位置: 首页 > 综合 > 正文

java 自定义监听器监听属性变化

2013年05月17日 ⁄ 综合 ⁄ 共 1400字 ⁄ 字号 评论关闭

 

java 自定义监听器监听属性变化
java 自定义监听器监听属性变化 
import java.util.EventObject;

public class MyEvent extends EventObject
{
 private Object obj;
 private String sName;

 public MyEvent(Object source,String sName)
 {
  super(source);
  this.obj=source;
  this.sName=sName;
 }

 public Object getObj()
 {
  return obj;
 }

 public String getsName()
 {
  return sName;
 }
}

import java.util.EventListener;

public interface MyEventListener extends EventListener
{

 public void handleEvent (MyEvent me);

}


import java.util.Iterator;
import java.util.Vector;

import demo.DemoEvent;

public class MyEventSource
{
 private Vector list=new Vector();
 private String   sName  = "";

  
 public MyEventSource()
 {
  super();
 }
 public void addMyEventListener(MyEventListener me)
 {
  list.add(me);
 }
 public void deleteMyEventListener(MyEventListener me)
 {
  list.remove(me);
 }
 public void notifyMyEvent(MyEvent me)
 {
  Iterator it=list.iterator();
  while(it.hasNext())
  {
    ((MyEventListener) it.next()).handleEvent(me); 
  }
 }
 public void setName(String str)
 {
  boolean bool = false;
  if (str == null && sName != null)
   bool = true;
  else if (str != null && sName == null)
   bool = true;
  else if (!sName.equals(str))
   bool = true;
  this.sName = str;
  // 如果改变则执行事件
  if (bool)
    notifyMyEvent(new MyEvent(this, sName));
 }
 public String getsName()
 {
  return sName;
 }
  
}

  

public class Test implements MyEventListener 
{
 public Test()
 {
  MyEventSource mes = new MyEventSource();
  mes.addMyEventListener(this);
  mes.setName("niu");
 }

 public static void main(String args[])
 {
  new Test();
 }

 public void handleEvent(MyEvent me) 
 {
  System.out.println(me.getSource());
  System.out.println(me.getsName());
 }
}

抱歉!评论已关闭.