事件狀態(tài)對象(Event State Object) 與事件發(fā)生有關(guān)的狀態(tài)信息一般都封裝在一個事件狀態(tài)對象中,這種對象是java.util.EventObject的子類。按設(shè)計習(xí)慣,這種事件狀態(tài)對象類的名應(yīng)以Event結(jié)尾。例如: public class MouseMovedExampleEvent extends java.util.EventObject { PRotected int x, y; /* 創(chuàng)建一個鼠標(biāo)移動事件MouseMovedExampleEvent */ MouseMovedExampleEvent(java.awt.Component source, Point location) { super(source); x = location.x; y = location.y; } /* 獲取鼠標(biāo)位置*/ public Point getLocation() { return new Point(x, y); }} 事件監(jiān)聽者接口與事件監(jiān)聽者
public void add< ListenerType>(< ListenerType> listener); public void remove< ListenerType>(< ListenerType> listener);
例如首先定義了一個事件監(jiān)聽者接口:
public interface ModelChangedListener extends java.util.EventListener { void modelChanged(EventObject e); }
接著定義事件源類: public abstract class Model { private Vector listeners = new Vector(); // 定義了一個儲存事件監(jiān)聽者的數(shù)組 /*上面設(shè)計格式中的< ListenerType>在此處即是下面的ModelChangedListener*/
public synchronized void addModelChangedListener (ModelChangedListener mcl) { listeners.addElement(mcl); }//把監(jiān)聽者注冊入listeners數(shù)組中 public synchronized void removeModelChangedListener(ModelChangedListener mcl) { listeners.removeElement(mcl); //把監(jiān)聽者從listeners中注銷 }