Java 事件触发接口回调方法
来源:互联网 发布:小米视频电视直播软件 编辑:程序博客网 时间:2024/06/05 10:18
其技巧就是:定义一个简单接口,并在该接口中声明我们要调用的方法,一般可以应用在键盘鼠标事件跟踪。
下面举一个例子:
假定我们希望在某个事件发生时得到通知。我们可以定义一个接口:
/*
* 在某个事件发生时得到通知.
*/
public interface InterestingEvent {
public void interestingEvent(); //其它方法体及方法定义也可.
}
此接口中的方法,是个没有返回值的也没有任何参数,如果您愿意也可以有返回值,也可以带参数.这就要看具体需求而定.
这使得我们可以控制实现该接口的类的任何对象。因此,我们不必关心任何外部类型信息。与在将 C++ 代码用于Motif 时使用窗口小部件的数据域来容纳对象指针的难以控制的 C 函数相比,这种方法要好得多。
实现接口的代码如下:
public class CallMe implements InterestingEvent {
public CallMe() {
}
public void interestingEvent() {
System.out.println("发生了CallMe事件,哈哈");
}
}
public class CallYou implements InterestingEvent {
public CallYou() {
}
public void interestingEvent() {
System.out.println("发生了CallYou事件,哈哈");
}
}
发出事件信号的类必须等待实现了 InterestingEvent 接口的对象,并在适当时候调用 interestingEvent() 方法。
public class EventNotifier {
private InterestingEvent ie; //接口对象引用
private boolean somethingHappened ;
public EventNotifier() {
somethingHappened = true ;
}
public void setInterestingEvent(InterestingEvent ie){ //参数引用附值
this.ie = ie ;
}
public void doWork(){
if(somethingHappened){
ie.interestingEvent();
}
}
}
下面做一下测试.
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
CallMe cm = new CallMe();
CallYou cy = new CallYou();
EventNotifier en = new EventNotifier();
en.setInterestingEvent(cm);
en.doWork();
en.setInterestingEvent(cy);
en.doWork();
}
}
此测试在发生指定的调用CalMe事件时,就扫行CallMe下的命令,如发生CallYou事件时,就调用CallYou下的命令.此种方法可以结合Command模式.实现MS-Windows 和 X Window System 事件驱动编程模型.
实际上采用了接口回调引用对象类,从而此对象实现方法调用.
- Java 事件触发接口回调方法
- Java 事件触发接口回调方法
- 初识java接口回调机制与androidView的触发事件回调
- java回车事件触发
- 使用连接触发事件方法
- JQuery触发事件的方法
- 用attachEvent()/addEventListener()方法添加触发事件
- 触发数据的事件对应查找方法
- 手动触发js事件的一种方法
- 解决FileSystemWatcher事件多次触发的方法
- JS中手动触发事件的方法
- submit() 方法不触发 onsubmit事件
- attachEvent()/addEventListener()方法添加触发事件
- Widget:notifyListeners方法---主动触发事件
- 用attachEvent()/addEventListener()方法添加触发事件
- js触发onchange事件的方法
- JS中手动触发事件的方法
- JS中手动触发事件的方法
- STL
- android phone电话调用流程
- iphone ios AV Foundation
- sql日期格式化
- 服务器网站搭建
- Java 事件触发接口回调方法
- 大学实训
- 36
- 浏览器兼容性问题
- case when用法
- 设备驱动学习笔记(1)----设备和模块的分类
- linux下如何产生core,调试core
- myocr
- Win2008快捷键汇总