请看程序:import java.awt.*;
import java.awt.event.*;
class MyWindow extends Frame implements ActionListener
{
TextField text1,text2,text3;
PoliceMan police;
MyWindow(String s)
{
super(s);
setLayout(new FlowLayout());
text1 = new TextField(10);
text2 = new TextField(10);
text3 = new TextField(10);
police = new PoliceMan(this);
add(text1);
add(text2);
add(text3);
addWindowListener(new MyWindowListener());
text1.addActionListener(this);
text3.addActionListener(this);
text1.addActionListener(police);
setBounds(100,100,150,150);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==text1)
{
int n=0, m=0;
try{
n=Integer.parseInt(text1.getText());
m=n*n;
text2.setText(n+"的平方是:"+m);
 }catch(Exception ee)
{
text1.setText("输入有误!");
}
}
else if(e.getSource()==text3)
{
text1.setText(null);
text2.setText(null);
text3.setText(null);
}
}
  public static void main(String [] args)
  {
   MyWindow win = new MyWindow("窗口");
  }
}
class PoliceMan implements ActionListener
{
MyWindow win = null;
PoliceMan(MyWindow a)
{
win = a;
}
public void actionPerformed(ActionEvent e)
{
int n =0,m=0;
  try{
n=Integer.parseInt(win.text1.getText());
m=n*n*n;
win.text3.setText(n+"的平方是:"+m);
 }catch(Exception ee)
{
win.text1.setText("输入有误!");
}
}
}
class MyWindowListener implements WindowListener
{
public void windowClosing(WindowEvent e)
{
e.getWindow().setVisible(false);
((Window)e.getComponent()).dispose();
System.exit(0);
}
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
}
请问,程序是怎么知道从众多Event类(如,WindowEvent,TextEvent,KeyEvent)当中选择用ActionEvent类来创建事件对象并把它传递给参数e?

解决方案 »

  1.   

    这些都是JVM去做的,不作我们操心了
      

  2.   

    Swing依赖于AWT1.1的事件处理机制,它基于AWT的授权事件模型。AWT的事件又分为语义事件和构件事件。当你的输入从文本组件提交后会产生一个构件事件和一个语义事件,文本组件根据你的构件事件会创建一个对应的语义事件,然后将这个语义事件发送给注册了的监听器。这些都是事件模型自己去做的,我们一般不需要关心,我们只需要按照事件处理机制,在适当的时候添加合适的事件监听,完成对事件的处理。
      

  3.   

    请问chenweionline是看那本书得到这个解释的?我也很想看看
      

  4.   

    Java 2 图形设计卷Ⅰ:AWT
    Graphic Java 1.2 Mastering the JFC Volume Ⅰ:AWT
    [美]David M.Geary 著 马欣民等译
    机械工业出版社有一些事件模型方面的内容,我有一个电子版,不过不太全,你可以看看。
    http://www.blogjava.net/leon/archive/2006/06/21/54138.html
      

  5.   

    谢谢chenweionline,终于可以圆满结贴了。