如何在Java中关闭AWT窗口

本文概述

  • 重写windowClosing()方法的不同方法
  • 关闭AWT窗口示例1:匿名类
  • 关闭AWT窗口示例2:扩展WindowAdapter
  • 关闭AWT窗口示例3:实现WindowListener
我们可以通过在windowClosing()方法内调用dispose()或System.exit()来关闭AWT窗口或框架。在WindowListener接口和WindowAdapter类中找到windowClosing()方法。
WindowAdapter类实现WindowListener接口。它提供了WindowListener接口的所有7种方法的默认实现。要覆盖windowClosing()方法, 可以使用WindowAdapter类或WindowListener接口。
如果实现WindowListener接口, 则将不得不重写WindowListener接口的所有7种方法。因此最好使用WindowAdapter类。
重写windowClosing()方法的不同方法 有许多方法可以覆盖windowClosing()方法:
  • 匿名班
  • 通过继承WindowAdapter类
  • 通过实现WindowListener接口
关闭AWT窗口示例1:匿名类
import java.awt.*; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class WindowExample extends Frame{ WindowExample(){ addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { dispose(); } }); setSize(400, 400); setLayout(null); setVisible(true); } public static void main(String[] args) { new WindowExample(); }

【如何在Java中关闭AWT窗口】输出:
如何在Java中关闭AWT窗口

文章图片
关闭AWT窗口示例2:扩展WindowAdapter
import java.awt.*; import java.awt.event.*; public class AdapterExample extends WindowAdapter{ Frame f; AdapterExample(){ f=new Frame(); f.addWindowListener(this); f.setSize(400, 400); f.setLayout(null); f.setVisible(true); } public void windowClosing(WindowEvent e) { f.dispose(); } public static void main(String[] args) { new AdapterExample(); } }

关闭AWT窗口示例3:实现WindowListener
import java.awt.*; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class WindowExample extends Frame implements WindowListener{ WindowExample(){ addWindowListener(this); setSize(400, 400); setLayout(null); setVisible(true); } public static void main(String[] args) { new WindowExample(); } public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowClosing(WindowEvent e) { dispose(); } public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent arg0) {} }

    推荐阅读