欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入
由于我们无权修改Java的编译器,所以我在这里将会借助于反射技术,利用一个事件委托类处理所有的点击事件,代码如下:
package cn.softworks.teachersearchsystem.support;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.lang.reflect.Method;/***该类是用来处理所有的Swing按钮点击事件,并根据将处理权<br>*转交给使用者来处理**@authorChen.yu**/publicclass EventHandlerimplements ActionListener { //组件所在的窗体对象 private Object form = null; //受到委托的方法名 private String methodName = null; /** *构造函数 * *@paramform 组件所在的窗体对象 *@parammethodName 受到委托的方法名 */ public EventHandler(Object form,String methodName) { this.form = form; this.methodName = methodName; } /** *事件处理委托方法 */ publicvoid actionPerformed(ActionEvent e) { //得到窗体对象的类型 Class formType = this.form.getClass();try {//得到指定委托方法的类型 Method method =formType.getMethod(this.methodName, new Class[] {e.getClass()}); //调用指定的方法 method.invoke(this.form, new Object[] {e}); }catch(Exception ex) { return; } }}
现在我们来编写一个测试程序,代码如下:
btnSearch.addActionListener(new EventHandler(this,”btnSearch_Click”));public void btnSearch_Click(ActionEvent e) { System.out.println(“This is btnSearch”);}
从以上代码中我们可以清晰的看到,事件处理和事件委托处于同一窗体中了,.Net方便的Delegate处理被我们用反射实现了。
[1][2]
总有一天,我会丢下我所有的疲倦和理想,