窗体监听事件WindowListener
EXIT_ON_CLOSE:结束窗口所在的应用程序。在窗口被关闭的时候会退出JVM。
DISPOSE_ON_CLOSE:隐藏当前窗口,并释放此窗体占有的资源。如果程序没有其他线程在运行,当所有窗口都被dispose后,JVM也会退出。
举例说明:关闭窗体A,窗体B也会退出。关闭窗体B,窗体A不会退出。
public class Demo{ public static void main(String[] args){ JFrame window1=new JFrame("窗体A"); JFrame window2=new JFrame("窗体B"); window1.setBounds(100,100,200,100); window2.setBounds(400,100,200,100); window1.setVisible(true); window2.setVisible(true); window1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); window2.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } }
【窗体监听事件 WindowListener】
windowOpened 打开
windowActivated 激活(获得焦点状态)
windowDeactivated 非激活(失去焦点状态)
windowIconified 最小化
windowDeiconified 最小化恢复正常
windowClosing 关闭(右上角X),优先于windowClosed
windowClosed 关闭,DISPOSE_ON_CLOSE时才会被调用
public class Demo extends JFrame { public Demo() { setBounds(100, 100, 300, 300); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setVisible(true); addWindowListener(new MyWindowListener());//调用方法类对象 } class MyWindowListener implements WindowListener { public void windowOpened(WindowEvent e) { System.out.println("窗体打开"); } public void windowClosing(WindowEvent e) { System.out.println("窗体关闭exit"); } public void windowClosed(WindowEvent e) { System.out.println("窗体关闭dispose"); } public void windowIconified(WindowEvent e) { System.out.println("窗体最小化"); } public void windowDeiconified(WindowEvent e) { System.out.println("窗体最小化恢复正常"); } public void windowActivated(WindowEvent e) { System.out.println("窗体激活"); } public void windowDeactivated(WindowEvent e) { System.out.println("窗体非激活"); } } public static void main(String[] args) { new Demo(); } }