spots
spots

Reputation: 75

How to invoke ShutdownHook thread with a window close operation of DISPOSE_ON_CLOSE or EXIT_ON_CLOSE

Assuming that Runtime.getRuntime().addShutdownHook(new Thread() has been set up correctly, how can the ShutdownHook thread be invoked when a Java application window (JFrame) is closed (in this case the only window) and the dispose window default close operation is DISPOSE_ON_CLOSE or EXIT_ON_CLOSE?

Note that for a quit command handled with a System.exit(0) which is then fed through the ShutdownHook thread, the application terminates correctly as all the associated threads are terminated before the Java application exits. So I want to accomplish the same thing by making the closing of the JFrame window go through the ShutdownHook thread clean up.

Upvotes: 1

Views: 2620

Answers (3)

Andrew Thompson
Andrew Thompson

Reputation: 168845

This works according to your spec. If I close the frame by clicking the X button, the shutdown hook is invoked.

import javax.swing.*;

class ShutDownHookDemo {

    public static void endMessage() {
        // clean up threads here..
        System.out.println("Thanks for using the app.");
    }

    public static void main(String[] args) {
        Thread t = new Thread() {
            public void run() {
                endMessage();
            }
        };
        Runtime.getRuntime().addShutdownHook(t);

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300,300);

        f.setVisible(true);
    }
}

Upvotes: 1

bestsss
bestsss

Reputation: 12066

frame.addWindowListener() and override windowClosed(WindowEvent e). From your question it looks you just need an event handling when the window gets closed.

good luck!

Upvotes: 2

camickr
camickr

Reputation: 324157

Runtime.getRuntime().addShutdownHook(...);

Upvotes: 0

Related Questions