2

This is a "best practices" type of question. AFAIK there are two approaches (and possibly more..) when needing to execute a task prior to JVM shutdown:

  1. Add a WindowListener to the container and override the windowClosing event
  2. Add a shutdown hook (i.e. Runtime.addShutdownHook)

Which approach is the "preferred" way when it comes to Java Desktop applications? Is there a "preferred" way?

mre
  • 43,520
  • 33
  • 120
  • 170

1 Answers1

1

not best practices, not preferred way, only to close current JVM instance and very simple,

1) Top-LevelContainer#setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

2) add WindowListener

     WindowListener exitListener = new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            int confirm = JOptionPane.showOptionDialog(null, 
                  "Are You Sure to Close Application?", "Exit Confirmation", 
                  JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, 
                  null, null, null);
            if (confirm == JOptionPane.YES_OPTION) {
                Top-LevelContainer#setVisible(false);
                // clean-up everything 

                // on error display  JOptionPane with error mgs but from
                // another JVM instance, e.g.jar file, see add 3.)
                System.exit(1); //in some cases not works System.exit(0);
            }
     }

3) here is rest for how to display error message from another, new JVM instance

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319