tags:

views:

145

answers:

4

Hi Is there any way to show joptionpane in shutdownhook i.e I need to show a confirmdailog in my shutdownhook event

+4  A: 

If there is, it won't help you.

The shutdown hooks are invoked asynchronously as part of the JVM shutdown, so a "confirm" dialog won't really confirm anything as you can't halt or reverse the shutdown process.

Kevin
Well, you can prevent the JVM from actually terminating by having a thread `wait()` forever but right, you can’t prevent an already running shutdown. :)
Bombe
You can't restart threads (such as the EDT) either.
Tom Hawtin - tackline
A: 

It seems like you want some sort of prompt when the user finishes with the program but hasn't done some commit action (close a document with unsaved changes). If that is the case, I would put a WindowListener on the window whose closing should trigger the prompt and override windowClosing(WindowEvent e) {...} to show your JOptionPane. According to the JavaDocs you can override the windowClosing at this time. This gives you an opportunity to have a "save, discard, cancel" diaglog for documents with unsaved changes.

KitsuneYMG
+1  A: 

I suspect what you want is not a shutdown hook, but a "really quit?" JOptionPane. If so, here's an example of how to do it:

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

public class ConfirmToCloseTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final JFrame frame = new JFrame();
                frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        if (JOptionPane.showConfirmDialog(frame, "Really quit?", "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                            System.exit(0);
                        }
                    }
                });
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.getContentPane().add(new JLabel("Hello world"));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}
Steve McLeod
+1  A: 

A shutdown hook is supposed to execute quickly. Waiting for a user to make a decision is not the kind of action a shutdown hook is meant for. A shutdown hook in an interactive program does not make sense. The real use case for shutdown hooks is for releasing resources and other housekeeping when the JVM is terminated abnormally.

Jeroen van Bergen