java小程序的窗口关闭问题

来源:百度知道 编辑:UC知道 时间:2024/05/05 18:24:01
第一个小程序:
import java.awt.*;
import java.awt.event.*;
public class TwoListen implements MouseListener,MouseMotionListener,WindowListener {
private Frame f;
private TextField tf;

public static void main(String argv[]){
TwoListen two=new TwoListen();
two.go();
}
public void go(){
f=new Frame("Two Listeners example");
f.add(new Label("click and drag the mouse"),"North");
tf=new TextField(30);
f.add(tf,"South");

f.addMouseListener( this);
f.addMouseMotionListener(this);
f.addWindowListener(this);
f.setSize(300,200);
f.setVisible(true);
}
public void mouseDragged(MouseEvent e){
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 mouseEnter

 
 
 
第二个不能正常关闭的原因是程序显示的窗口(private Frame f)的 windowClosing 事件没有和终止程序的语句挂钩。

其实万事俱备只欠东风,因为程序里的 Interfaceforme 类是个截取 windowClosing 事件后马上终止程序的窗口事件监听器,
所以在 go( ) 方法里实例化 Frame 之后的任何地方直接加一句 f.addWindowListener( this ); 即解决了问题。
 
 
 

本来就不能啊

import java.awt.*;
import java.awt.event.*;
public class Interfaceforme extends WindowAdapter{
private Frame f;
private Button b;

public static void main(String args[]){
Interfaceforme face=new Interfaceforme();
face.go();
}
public void go(){
f=new Frame("Two Listeners example");
f.add(new Label("click and drag the mouse"),"North");
b=new Button("hi");
f.add(b,"South");

f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(1);
}
}