java中的事件定义_Java中定义事件

我们在JFrame、awt或swing中了解过事件的概念。如MouseEvent, KeyEvent, WindowEvent。

JDK就像给我们提供了框架结构一样,提供了设计事件和监听的方法。

1.设计一个事件

import java.util.EventObject;

public class DemoEvent extends EventObject {

Object obj;

public DemoEvent(Object source)

{

super(source);

// TODO Auto-generated constructor stub

obj = source;

}

public Object getSource()

{

return obj;

}

public void say()

{

System.out.println("This is say method...");

}

}

2.设计事件源

import java.util.Enumeration;

import java.util.Vector;

//import java.util.*;

public class DemoSource

{

private Vector repository = new Vector();

DemoListener dl;

public DemoSource()

{

}

public void addDemoListener(DemoListener dl)//添加监听

{

repository.addElement(dl);

}

public void notifyDemoEvent()

{

Enumeration enum1 = repository.elements();

while(enum1.hasMoreElements())

{

dl = (DemoListener)enum1.nextElement();

dl.demoEvent(new DemoEvent(this));

}

}

}

3.设计监听接口

import java.util.EventListener;

public interface DemoListener extends EventListener {

public void demoEvent(DemoEvent dm);

}

4.定义3个监听器(三个监听器,监听到后说的内容区别开)

Listener1.java

public class Listener1 implements DemoListener

{

public void demoEvent(DemoEvent de)

{

System.out.println("Inside listener1...");

}

}

Listener2.java

package demo.listener;

public class Listener2 implements DemoListener

{

public void demoEvent(DemoEvent de)

{

System.out.println("Inside listener2...");

}

}

Listener3.java

package demo.listener;

public class Listener3 implements DemoListener

{

public void demoEvent(DemoEvent de)

{

System.out.println("Inside listener3...");

}

}

5.测试类

public class TestDemo

{

DemoSource ds;

public TestDemo()

{

try{

ds = new DemoSource();

Listener1 l1 = new Listener1();

Listener2 l2 = new Listener2();

Listener3 l3 = new Listener3();

ds.addDemoListener(l1);

ds.addDemoListener(l2);

ds.addDemoListener(l3);

ds.notifyDemoEvent();

}catch(Exception ex){ex.printStackTrace();}

}

public static void main(String args[])

{

new TestDemo();

}

}

测试结果是:

Inside listener1...

Inside listener2...

Inside listener3...

你可能感兴趣的:(java中的事件定义)