1 public class WindowListenerKnow extends JFrame 2 { 3 public WindowListenerKnow() 4 { 5 this.setBounds(300, 100, 400, 400); 6 this.setTitle("我是测试【x】按钮关闭方法的"); 7 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 8 } 9 public void init() 10 { 11 12 } 13 public static void main(String[] args) 14 { 15 WindowListenerKnow windowListenerKnow = new WindowListenerKnow(); 16 windowListenerKnow.setVisible(true); 17 } 18 19 /** 20 * 这里需要重写窗口的事件中转方法,而不是实现WindowListener接口,因为程序时从这个方法processWindowEvent进入到窗口关闭事件的 21 */ 22 @Override 23 protected void processWindowEvent(WindowEvent e) 24 { 25 //这里需要对进来的WindowEvent进行判断,因为,不仅会有窗口关闭的WindowEvent进来,还可能有其他的WindowEvent进来 26 if (e.getID() == WindowEvent.WINDOW_CLOSING) 27 { 28 int option = JOptionPane.showConfirmDialog(null, "是否关闭程序?", "程序退出提示", JOptionPane.OK_CANCEL_OPTION); 29 if (option == JOptionPane.OK_OPTION) 30 { 31 super.processWindowEvent(e); 32 } 33 else { 34 //用户选择不退出本程序,因此可以继续留在本窗口 35 } 36 } 37 else { 38 super.processWindowEvent(e); 39 } 40 } 41 }