Adding Joptionpane to shutdownHook
I suspect what you want is not shutdown but "really quit smoking"? 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);
}
});
}
}
source to share
The shutdown tap is expected to be completed quickly. Waiting for the user to make a decision is not the kind of action that shutdown is intended to do. A closure in an interactive program is meaningless. Real use case for disabling hooks for freeing resources and other households when the JVM terminates abnormally.
source to share
It seems that you need some sort of prompt when the user finishes using the program but hasn't performed any commit action (close the document with unsaved changes). If so, I would put a WindowListener on a window whose closing should trigger a prompt and override windowClosing (WindowEvent e) {...} to show your JOptionPane. According to JavaDocs, you can override windowClosing at this time. This gives you the ability to "save, discard, discard" the diaglog for documents with unsaved changes.
source to share