登录  
 加关注
查看详情
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

学无止境

一点积累,与大家分享

 
 
 

日志

 
 

java.util.EventObject 用来广播事件  

2010-05-18 14:02:58|  分类: java技术 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
Java做观察者模式:
1、事件 ( extends EventObject)
2、观察 ( EventListener)
3、侦听(EventSource)
===========
A new custom event must extends EventObject. Moreover, an event listener interface must be declared to allow objects to receive the new custom event. All listeners must extend from EventListener.

1、事件,继承EventObject事件

This example demonstrates all the steps necessary to create a new custom event.

 // Declare the event. It must extend EventObject.
public class MyEvent extends EventObject {
public MyEvent(Object source) {
super(source);
}
}

2、监听接口,继承EventListener,必须实现事件接口
// Declare the listener class. It must extend EventListener.
// A class must implement this interface to get MyEvents.
public interface MyEventListener extends EventListener {
public void myEventOccurred(MyEvent evt);
}
3、事件源类 完成注册、通知(发布者类,类似在c#中发布者
// Add the event registration and notification code to a class.
public class MyClass {
// Create the listener list
protected javax.swing.event.EventListenerList listenerList =
new javax.swing.event.EventListenerList();

// This methods allows classes to register for MyEvents
public void addMyEventListener(MyEventListener listener) {
listenerList.add(MyEventListener.class, listener);
}

// This methods allows classes to unregister for MyEvents
public void removeMyEventListener(MyEventListener listener) {
listenerList.remove(MyEventListener.class, listener);
}
public Notify(){
fireMyEvent(new MyEvent());
}
// This private class is used to fire MyEvents
void fireMyEvent(MyEvent evt) {
Object[] listeners = listenerList.getListenerList();
// Each listener occupies two elements - the first is the listener class
// and the second is the listener instance
for (int i=0; i<listeners.length; i+=2) {
if (listeners[i]==MyEventListener.class) {
((MyEventListener)listeners[i+1]).myEventOccurred(evt);
}
}
}
}
Here's an example of how to register for MyEvents.
 MyClass c = new MyClass();

// Register for MyEvents from c
c.addMyEventListener(new MyEventListener() {
public void myEventOccurred(MyEvent evt) {
// MyEvent was fired
}
 });
c.Notify();
  评论这张
 
阅读(2032)| 评论(0)

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018