学习处理事件时,必须很好的掌握事件源,监视器,处理事件的接口
1.事件源
能够产生java认可事件的对象都可称为事件源,也就是说事件源必须是对象
2.监视器
监视事件源,以便对发生的事件做出处理
如:对文本框,这个方法为:
addActionListener(监视器);
3.处理事件的接口
为了让监视器这个对象能对事件源发生的事件进行处理,创建该监视器对象的类必须声明实现相应的接口,即必须在类体中给出该接口中所有方法的方法体
java.awt.event包中提供了许多事件类和处理各种事件的接口。
对于文本框,这个接口的名字是ActionListener,这个接口的唯一方法为:public void actionPerformed(ActionEvent e)
为了能监视到ActionEvent类型的事件,事件源必须使用addActionListener方法获得监视器,创建监视器的类必须实现接口ActionListener
ActionEvent类有如下常用方法:
1. public Object getSource()
ActionEvent对象调用该方法可以获取发生ActionEvent事件的事件源对象的引用
2. public String getActionCommand()
ActionEvent对象调用该方法可以获取发生ActionEvent事件时,和该事件相关的一个命令字符串
注意:创建监视器对象的类必须声明实现相应的接口:
class A implements xxxListener
实战演练:当用户在文本框text1中输入英语单词并按Enter键,文本框text3中立即显示汉语意思;在文本框text2中中输入汉语单词并按Enter键后,文本框text3中立即显示英文意思代码如下:
import java.awt.*;
import java.awt.event.*;
class Mywindow extends Frame implements ActionListener
{
TextField text1,text2,text3;
Mywindow(String s){
setTitle(s);
setLayout(new FlowLayout());
text1=new TextField(8);
text2=new TextField(8);
text3=new TextField(15);
add(text1);
add(text2);
add(text3);
text1.addActionListener(this);
text2.addActionListener(this);
setBounds(100,100,150,150);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==text1)
{
String word=text1.getText();
if(word.equals("boy"))
{
text3.setText("男孩");
}
else if(word.equals("girl"))
{
text3.setText("女孩");
}
else if(word.equals("sun"))
{
text3.setText("太阳");
}
else
{
text3.setText("没有该单词");
} }
else if(e.getSource()==text2)
{
String word=text2.getText();
if(word.equals("男孩"))
{
text3.setText("boy");
}
else if(word.equals("女孩"))
{
text3.setText("girl");
}
else if(word.equals("太阳"))
{
text3.setText("sun");
}
else
{
text3.setText("没有该单词");
} }
}
}
public class Example3
{
public static void main(String[] args){
Mywindow win=new Mywindow("汉英互译");
}
}