1.使用JFrame的enableEvents和processWindowEvent
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainFrame extends JFrame {
public MainFrame() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
this.setSize(new Dimension(465, 219));
this.setTitle("JLabelDemo1");
}
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
}
}
}
2.JFrame的关闭方法:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);