Java事件和事件侦听器 [英] Java events and event listeners
问题描述
制作自定义事件(非GUI相关事件)和处理程序的方式。有些人可以提供一个关于如何创建自定义事件和监听器的简单说明?
你基本上创建一个接口作为监听器,如
public interface EatListener {
...
} $ b您可以在EatListener类中使用$ b
,您可以使用事件调用方法作为方法的参数;例如
public void onEat(EatEvent);
那么你可以有一个类,像Human实现或实例化一个EatListener;例如
public class Human {
private EatListener listener;
public void eatFood(食物食物){
if(listener!= null){
listener.onEat(new EatEvent(food));
}
}
}
那么你需要有实际的EatEvent;这可以像食物的包装一样简单,可能还有一些额外的数据。
与任何GUI上的GUI一样,您可以从该界面创建匿名内部类:
new EatListener(){
public void onEat(EatEvent event){
System.out.println(I just ate+ event.getFood()。getName());
}
}
I searched on Google to learn how to create custom events and event listeners. After reading some articles about it, I'm still confused. I would like to ask you guys for a review of the ways for making custom events (non-GUI related events) and handlers. Can some provide a simple explanation on how to create custom events and listeners?
You basically create an interface as the listener such as
public interface EatListener {
...
}
inside the EatListener class, you have method that you call with the event as the method's parameter; such as
public void onEat(EatEvent);
then you can have a class like Human that implements or instantiates an EatListener; such as
public class Human {
private EatListener listener;
public void eatFood(Food food) {
if(listener != null) {
listener.onEat(new EatEvent(food));
}
}
}
then you need to have the actual EatEvent; which can be as simple as wrapper for food with possibly some extra data.
As with any GUI on java you can create anonymous inner classes from that interface:
new EatListener() {
public void onEat(EatEvent event) {
System.out.println("I just ate " + event.getFood().getName());
}
}
这篇关于Java事件和事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!