Readers who have studied Java swing must be puzzled by the relatively complex event-driven model in swing, although the event-driven model is completely embodied in the Java swing, but for a software beginner this is almost "nude" The event-driven model is really hard to understand.
The Microsoft. NET Framework is much simpler than the GUI programming of Java Swing and is also an event-driven model. NET Framework for a large number of encapsulation processing,. NET refers to this encapsulation as a delegate (Delegate) whose code is as follows:
//当btnSubmit按钮被点击以后要求交给btnSubmit_Click方法处理
// EventHandler在中间启到委托器的作用,
//它负责将事件分发到指定的方法中进行处理
this.btnSubmit.Click += new EventHandler(this.btnSubmit_Click);
//事件处理方法
// object sender:事件源,这里指btnSubmit对象
// EventArgs e:事件处理参数,它保存了需要提供给程序员的必要信息
private void btnSubmit_Click(object sender, EventArgs e)
{
//打印This is a button语句
System.Diagnostics.Debug.WriteLine("This is button");
}
In contrast, it is much more complicated to look at the event handling and delegation of Java Swing: The code is as follows: (if you are not quite familiar with the swing event driver, you can refer to my other article: event-driven Model instance details (Java article)):
//为btnSubmit增加侦听器SelectHandler,当btnSubmit被点击以后
//有侦听器的actionPerformed负责处理该点击事件的业务
//由于事件源btnSubmit和侦听器类SelectHandler处于两个不同的类中
//为了让SelectHandler类取得页面的信息,我们需要将窗体对象(this)
//传入到侦听器中
btnSubmit.addActionListener(new SelectHandler(this));
//侦听器SelectHandler,它必须实现动作事件ActionListener接口
//以达到事件分发的作用
class SelectHandler implements ActionListener {
private CommonDialogDemo form = null;
//将窗体对象CommonDialogDemo通过构造函数传入SelectHandler类中
public SelectHandler(CommonDialogDemo form) {
this.form = form;
}
//事件处理方法,当btnSubmit被点击,自动执行以下打印代码
publicvoid actionPerformed(ActionEvent e) {
System.out.println("This is button");
}
}