实现代码:
TestFrame.java文件的内容:
import java.awt.*;
public class TestFrame {
public static void main(String[] args) {
// System.out.println("haha");
Frame f = new Frame("I love you!");
f.add(new Button("ok"));
f.setSize(300, 300);
f.setVisible(true);
f.addWindowListener(new MyWindowListener()); // 注册事件监听器
}
}
MyWindowListener.java文件的内容:
import java.awt.*;
import java.awt.event.*;
public class MyWindowListener implements WindowListener {
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
e.getWindow().setVisible(false);
((Window) e.getComponent()).dispose();
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
}
这样就是的上例中的窗口能通过“X”按钮关闭。