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


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

  1. import java.util.EventObject;  
  2.   
  3. public class MyEvent extends EventObject  
  4. {  
  5.  private Object obj;  
  6.  private String sName;  
  7.   
  8.  public MyEvent(Object source,String sName)  
  9.  {  
  10.   super(source);  
  11.   this.obj=source;  
  12.   this.sName=sName;  
  13.  }  
  14.   
  15.  public Object getObj()  
  16.  {  
  17.   return obj;  
  18.  }  
  19.   
  20.  public String getsName()  
  21.  {  
  22.   return sName;  
  23.  }  
  24. }  
  25.   
  26. import java.util.EventListener;  
  27.   
  28. public interface MyEventListener extends EventListener  
  29. {  
  30.   
  31.  public void handleEvent (MyEvent me);  
  32.   
  33. }  
  34.   
  35.   
  36. import java.util.Iterator;  
  37. import java.util.Vector;  
  38.   
  39. import demo.DemoEvent;  
  40.   
  41. public class MyEventSource  
  42. {  
  43.  private Vector list=new Vector();  
  44.  private String   sName  = "";  
  45.   
  46.     
  47.  public MyEventSource()  
  48.  {  
  49.   super();  
  50.  }  
  51.  public void addMyEventListener(MyEventListener me)  
  52.  {  
  53.   list.add(me);  
  54.  }  
  55.  public void deleteMyEventListener(MyEventListener me)  
  56.  {  
  57.   list.remove(me);  
  58.  }  
  59.  public void notifyMyEvent(MyEvent me)  
  60.  {  
  61.   Iterator it=list.iterator();  
  62.   while(it.hasNext())  
  63.   {  
  64.     ((MyEventListener) it.next()).handleEvent(me);   
  65.   }  
  66.  }  
  67.  public void setName(String str)  
  68.  {  
  69.   boolean bool = false;  
  70.   if (str == null && sName != null)  
  71.    bool = true;  
  72.   else if (str != null && sName == null)  
  73.    bool = true;  
  74.   else if (!sName.equals(str))  
  75.    bool = true;  
  76.   this.sName = str;  
  77.   // 如果改变则执行事件  
  78.   if (bool)  
  79.     notifyMyEvent(new MyEvent(this, sName));  
  80.  }  
  81.  public String getsName()  
  82.  {  
  83.   return sName;  
  84.  }  
  85.     
  86. }  
  87.   
  88.     
  89.   
  90. public class Test implements MyEventListener   
  91. {  
  92.  public Test()  
  93.  {  
  94.   MyEventSource mes = new MyEventSource();  
  95.   mes.addMyEventListener(this);  
  96.   mes.setName("niu");  
  97.  }  
  98.   
  99.  public static void main(String args[])  
  100.  {  
  101.   new Test();  
  102.  }  
  103.   
  104.  public void handleEvent(MyEvent me)   
  105.  {  
  106.   System.out.println(me.getSource());  
  107.   System.out.println(me.getsName());  
  108.  }  
  109. }  

相关内容