AWT Window Close Listener/Event

alexmherrmann picture alexmherrmann · Aug 16, 2011 · Viewed 41.4k times · Source

I am sorry if this is a n00b question, but I have spent way too long for this once I create the Window listener, window event, and everything else, how do I specify what method to invoke? Here is my code:

private static void mw() {
    Frame frm = new Frame("Hello Java");
    WindowEvent we = new WindowEvent(frm, WindowEvent.WINDOW_CLOSED);
    WindowListener wl = null;
    wl.windowClosed(we);
    frm.addWindowListener(wl);
    TextField tf = new TextField(80);
    frm.add(tf);
    frm.pack();
    frm.setVisible(true);

}

I am trying to get a URL, and Download it, I have everything else worked out, I am just trying to get the window to close.

Answer

Andrew Thompson picture Andrew Thompson · Aug 16, 2011

Window closing method

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class FrameByeBye {

    // The method we wish to call on exit.
    public static void showDialog(Component c) {
        JOptionPane.showMessageDialog(c, "Bye Bye!");
    }

    public static void main(String[] args) {
        // creating/udpating Swing GUIs must be done on the EDT.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                final JFrame f = new JFrame("Say Bye Bye!");
                // Swing's default behavior for JFrames is to hide them.
                f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                f.addWindowListener( new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent we) {
                        showDialog(f);
                        System.exit(0);
                    }
                } );
                f.setSize(300,200);
                f.setLocationByPlatform(true);
                f.setVisible(true);

            }
        });
    }
}

Also look into Runtime.addShutdownHook(Thread) for any action that is vital to perform before shutting down.

AWT

Here is an AWT version of that code.

import java.awt.*;
import java.awt.event.*;

class FrameByeBye {

    // The method we wish to call on exit.
    public static void showMessage() {
        System.out.println("Bye Bye!");
    }

    public static void main(String[] args) {
        Frame f = new Frame("Say Bye Bye!");
        f.addWindowListener( new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {
                showMessage();
                System.exit(0);
            }
        } );
        f.setSize(300,200);
        f.setLocationByPlatform(true);
        f.setVisible(true);
    }
}