java 自定义事件的触发及监听
发布网友
发布时间:2022-04-27 04:32
我来回答
共4个回答
热心网友
时间:2022-06-26 06:44
JAVA事件响应机制
1,先自定义一个事件
public class MyEvent extends java.util.EventObject{
public MyEvent(Object source)
{
super(source);
}
}
2,再自定义一个*
public class MyListener implements java.util.EventListener{
//这里是当事件发生后的响应过程
public void EventActivated(MyEvent me)
{
System.out.println("事件已经被触发");
}
}
3,以下这个类为触发事件的事件源
public class MyObject {
private Vector vectorListeners=new Vector();
public synchronized void addMyListener(MyListener ml)
{
vectorListeners.addElement(ml);
}
public synchronized void removeMyListener(MyListener ml)
{
vectorListeners.removeElement(ml);
}
protected void activateMyEvent()
{
Vector tempVector=null;
MyEvent e=new MyEvent(this);
synchronized(this)
{
tempVector=(Vector)vectorListeners.clone();
for(int i=0;i<tempVector.size();i++)
{
MyListener ml=(MyListener)tempVector.elementAt(i);
ml.EventActivated(e);
}
}
}
//定义一个公用方法用于触发事件
public void test()
{
activateMyEvent();
}
}
4,测试类
public class Test {
public static void main(String[] args)
{
MyObject mo=new MyObject();
//注册该事件
mo.addMyListener(new MyListener());
//触发该事件
mo.test();
}
}
热心网友
时间:2022-06-26 06:44
import java.awt.event.*;
import java.util.*;
interface MyListener
{
void begin(First first);
}
class Control implements MyListener
{
First first;public void newGame(First first)
{
this.first = first;
first.start();
}
@Overridepublic void begin(First firstone)
{
System.out.println("second go on");
}
}
class First
{
private Set<MyListener>listeners = new HashSet<MyListener>();
public void action()
{
System.out.println("First begin");
}
private class FirstThread implements Runnable
{
public void run()
{
while (true)
{
action();
for (MyListener sl : listeners)
{sl.begin(First.this);
}
try {Thread.sleep(1000);}
catch (InterruptedException e)
{e.printStackTrace();}
}
}
}
public void start()
{
new Thread(new FirstThread()).start();
}
public void addMyListener(MyListener ml)
{
if (ml != null)
{listeners.add(ml);
}
}
}
public class TestEvent
{public static void main(String args[])
{
First first = new First();
Control c = new Control();
first.addMyListener(c);
c.newGame(first);
}
}
运行结果
First begin
second go on
First begin
second go on
First begin
second go on
First begin
second go on
热心网友
时间:2022-06-26 06:45
创建一个监视器喽
热心网友
时间:2022-06-26 06:46
其实这东西归咎到底就是一个监听者模式,自己写一个就行了~关于监听者模式网上的资料比较多,自己查查就行了。