2、Java 2事件处理模型
在Java1.0事件处理模型中事件处理是以如下方法执行的。deliverEvent()用于决定事件的目标,目标是处理事件的组件或容器,此过程开始于GUI层的最外部而向内运作。
当按一个button时,如果检测到是该按钮激发的事件,该按钮会访问它的deliverEvent()方法,这一操作由系统完成。一旦识别目标组件,正确事件类型发往组件的postEvent()方法,该方法依次把事件送到handleEvent()方法并且等待方法的返回值。
"true"表明事件完全处理,"false"将使postEvent()方法联系目标容器,希望完成事件处理。
下面给一个实例:
import java.applet.*;
import java.awt.*;
public class Button1Applet
extends Applet{
public void init()
{
add(new Button("Red"));
add(new Button("Blue"));
}
public boolean action
(Enent evt,Object whatAction)
{
if( !( evt.target
instanceof Button))return false;
String buttonlabel=
(String)whatAction;
if(buttonlabel=="Red")
setBackground(Color.red);
if(buttonlabel==" Blue")
setBackground(Color.blue);
repaint();
return true;
}
}
在Java2处理事件时,没有采用dispatchEvent()-postEvent()-handleEvent()方式,采用了监听器类,每个事件类都有相关联的监听器接口。事件从事件源到监听者的传递是通过对目标监听者对象的Java方法调用进行的。
对每个明确的事件的发生,都相应地定义一个明确的Java方法。这些方法都集中定义在事件监听者(EventListener)接口中,这个接口要继承 java.util.EventListener。 实现了事件监听者接口中一些或全部方法的类就是事件监听者。
伴随着事件的发生,相应的状态通常都封装在事件状态对象中,该对象必须继承自java.util.EventObject。事件状态对象作为单参传递给应响应该事件的监听者方法中。发出某种特定事件的事件源的标识是:遵从规定的设计格式为事件监听者定义注册方法,并接受对指定事件监听者接口实例的引用。
有时,事件监听者不能直接实现事件监听者接口,或者还有其它的额外动作时,就要在一个源与其它一个或多个监听者之间插入一个事件适配器类的实例,来建立它们之间的联系。我们来看下面一个简单的实例:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleExample extends JFrame
{
JButton jButton1 = new JButton();
public SimpleExample()
{
try {
jbInit();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void
main(String[] args)
{
SimpleExample simpleExample
= new SimpleExample();
}
private void jbInit()
throws Exception {
jButton1.setText
("jButton1");
jButton1.addActionListener(new SimpleExample_jButton1_actionAdapter(this));
jButton1.addActionListener(new SimpleExample_jButton1_actionAdapter(this));
this.getContentPane().add
(jButton1, BorderLayout.CENTER);
this.setVisible(true);
}
void jButton1_actionPerformed
(ActionEvent e)
{
System.exit(0);
}
}
class SimpleExample_jButton1_
actionAdapter implements
java.awt.event.ActionListener
{
SimpleExample adaptee;
SimpleExample_jButton1_actionAdapter
(SimpleExample adaptee)
{
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e)
{
adaptee.jButton1_actionPerformed(e);
}
}
| 共7页: 上一页 [1] 2 [3] [4] [5] [6] [7] 下一页 | ||
|