java中怎样自定义监听器

zhanghuaigong 2010-05-24 05:10:38
java中怎样定义自己的监听器?
...全文
631 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
tx183584 2010-05-24
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 zhanghuaigong 的回复:]

有的书上并没有实现什么接口,而是自定义的监听器接口,然后自己实现,还要自己写一个添加监听器方法,不太懂,谁知道是怎么回事?
[/Quote]
继承这个接口的类吧
huntor 2010-05-24
  • 打赏
  • 举报
回复
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.
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);
}
}

// 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);
}

// 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);
}

// 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
}
});


zhanghuaigong 2010-05-24
  • 打赏
  • 举报
回复
有的书上并没有实现什么接口,而是自定义的监听器接口,然后自己实现,还要自己写一个添加监听器方法,不太懂,谁知道是怎么回事?
yusongbin 2010-05-24
  • 打赏
  • 举报
回复
实现监听接口
csupanmin 2010-05-24
  • 打赏
  • 举报
回复
实现ActionListener接口或者是继承接听器适配类
zhanghuaigong 2010-05-24
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 mybeautiful 的回复:]
监听什么,问题没有描述清楚.
[/Quote]
比如在做贪吃蛇的时候蛇每次移动都要进行一些处理。怎样自定义监听器监听蛇的移动?
piaolankeke 2010-05-24
  • 打赏
  • 举报
回复
swing 或 awt中的ActionListener?
Mybeautiful 2010-05-24
  • 打赏
  • 举报
回复
监听什么,问题没有描述清楚.

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧