Adding Joptionpane to shutdownHook

Is there a way to show joptionpane in shutdownhook ie I need to show confirmdailog in my shutdownhook event

+2


source to share


4 answers


If there is, it won't help.



Shutdown hooks are called asynchronously as part of the JVM shutdown, so the "confirm" dialog will not confirm anything, since you cannot stop or cancel the shutdown process.

+5


source


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);
            }
        });
    }

}

      

+1


source


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.

+1


source


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.

0


source







All Articles