例5.10
import java.awt.*;
import java.awt.event.*;
public class ThreeListener implements MouseMotionListener,MouseListener,WindowListener
{
//实现了三个接口
private Frame f;
private TextField tf;
public static void main(String args[])
{
ThreeListener two = new ThreeListener();
two.go(); }
public void go() {
f = new Frame("Three listeners example");
f.add(new Label("Click and drag the mouse"),"North");
tf = new TextField(30);
f.add(tf,"South"); //使用缺省的布局管理器
f.addMouseMotionListener(this); //注册监听器MouseMotionListener
f.addMouseListener(this); //注册监听器MouseListener
f.addWindowListener(this); //注册监听器WindowListener
f.setSize(300,200);
f.setVisible(true);
}
public void mouseDragged (MouseEvent e)
{
//实现mouseDragged方法
String s = "Mouse dragging : X="+e.getX()+"Y
= "+e.getY();
tf.setText(s);
}
public void mouseMoved(MouseEvent e){}
//对其不感兴趣的方法可以方法体为空
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){
String s = "The mouse entered";
tf.setText(s);
}
public void mouseExited(MouseEvent e){
String s = "The mouse has left the building";
tf.setText(s);
}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){ }
public void windowClosing(WindowEvent e) {
//为了使窗口能正常关闭,程序正常退出,需要实现windowClosing方法
System.exit(1);
}
public void windowOpened(WindowEvent e) {}
//对其不感兴趣的方法可以方法体为空
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent e) { }
public void windowDeactivated(WindowEvent e) {}
}
上例中有如下几个特点:
1.可以声明多个接口,接口之间用逗号隔开。
……implements MouseMotionListener, MouseListener, WindowListener;
2.可以由同一个对象监听一个事件源上发生的多种事件:
f.addMouseMotionListener(this);
f.addMouseListener(this);
f.addWindowListener(this);
则对象f 上发生的多个事件都将被同一个监听器接收和处理。
3.事件处理者和事件源处在同一个类中。本例中事件源是Frame f,事件处理者是类ThreeListener,其中事件源Frame
f是类ThreeListener的成员变量。
4.可以通过事件对象获得详细资料,比如本例中就通过事件对象获得了鼠标发生时的坐标值。
public void mouseDragged(MouseEvent e) {
String s="Mouse dragging :X="+e.getX()+"Y="+e.getY();
tf.setText(s);
}
Java语言类的层次非常分明,因而只支持单继承,为了实现多重继承的能力,Java用接口来实现,一个类可以实现多个接口,这种机制比多重继承具有更简单、灵活、更强的功能。在AWT中就经常用到声明和实现多个接口。记住无论实现了几个接口,接口中已定义的方法必须一一实现,如果对某事件不感兴趣,可以不具体实现其方法,而用空的方法体来代替。但却必须所有方法都要写上。
|