java事件機制包括三個部分:事件、事件監聽器、事件源。
1、事件。一般繼承自java.util.EventObject類,封裝了事件源對象及跟事件相關的信息。
com.javaedu.event.CusEvent類
- package com.javaedu.event;
- import java.util.EventObject;
- /**
- * 事件類,用於封裝事件源及一些與事件相關的參數.
- * @author Eric
- */
- public class CusEvent extends EventObject {
- private static final long serialVersionUID = 1L;
- private Object source;//事件源
- public CusEvent(Object source){
- super(source);
- this.source = source;
- }
- public Object getSource() {
- return source;
- }
- public void setSource(Object source) {
- this.source = source;
- }
- }
2、事件監聽器。實現java.util.EventListener接口,註冊在事件源上,當事件源的屬性或狀態改變時,取得相應的監聽器調用其內部的回調方法。
com.javaedu.event.CusEventListener類
- package com.javaedu.event;
- import java.util.EventListener;
- /**
- * 事件監聽器,實現java.util.EventListener接口。定義回調方法,將你想要做的事
- * 放到這個方法下,因爲事件源發生相應的事件時會調用這個方法。
- * @author Eric
- */
- public class CusEventListener implements EventListener {
- //事件發生後的回調方法
- public void fireCusEvent(CusEvent e){
- EventSourceObjecteObject = (EventSourceObject)e.getSource();
- System.out.println("My name has been changed!");
- System.out.println("I got a new name,named \""+eObject.getName()+"\""); }
- }
3、事件源。事件發生的地方,由於事件源的某項屬性或狀態發生了改變(比如BUTTON被單擊、TEXTBOX的值發生改變等等)導致某項事件發生。換句話說就是生成了相應的事件對象。因爲事件監聽器要註冊在事件源上,所以事件源類中應該要有盛裝監聽器的容器(List,Set等等)。
com.javaedu.event.EventSourceObject類
- package com.javaedu.event;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.Set;
- /**
- * 事件源.
- * @author Eric
- */
- public class EventSourceObject {
- private String name;
- //監聽器容器
- private Set<CusEventListener> listener;
- public EventSourceObject(){
- this.listener = new HashSet<CusEventListener>();
- this.name = "defaultname";
- }
- //給事件源註冊監聽器
- public void addCusListener(CusEventListener cel){
- this.listener.add(cel);
- }
- //當事件發生時,通知註冊在該事件源上的所有監聽器做出相應的反應(調用回調方法)
- protected void notifies(){
- CusEventListener cel = null;
- Iterator<CusEventListener> iterator = this.listener.iterator();
- while(iterator.hasNext()){
- cel = iterator.next();
- cel.fireCusEvent(new CusEvent(this));
- }
- }
- public String getName() {
- return name;
- }
- //模擬事件觸發器,當成員變量name的值發生變化時,觸發事件。
- public void setName(String name) {
- if(!this.name.equals(name)){
- this.name = name;
- notifies();
- }
- }
- }
下面是主方法類
com.javaedu.event.MainTest類、
- package com.javaedu.event;
- public class MainTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- EventSourceObject object = new EventSourceObject();
- //註冊監聽器
- object.addCusListener(new CusEventListener(){
- @Override
- public void fireCusEvent(CusEvent e) {
- super.fireCusEvent(e);
- }
- });
- //觸發事件
- object.setName("eric");
- }
- }
轉自:http://ericliu1986.iteye.com/blog/629562