Exiting an application gracefully?

前端 未结 3 437
不知归路
不知归路 2021-01-12 10:06

I have an application with a well defined Try/Catch/Finally chain that exits and executes the finally block just fine under normal conditions, however when someone premature

3条回答
  •  迷失自我
    2021-01-12 11:06

    With modern Java, Window.dispose() on all application windows can offer more graceful possibility to exit an AWT application than System.exit(0), see
    https://docs.oracle.com/javase/8/docs/api/java/awt/Window.html#dispose--

    /** Listens and closes AWT windows.
     * The class is implemented as singleton since only one is needed.
     */
    public class ExitListener extends WindowAdapter {
    
      /** the instance object */
      private static final ExitListener INSTANCE = new ExitListener();
    
      // hide the constructor
      private ExitListener () {}
    
      /** retrieve the listener object */
      public static ExitListener getInstance () {
        return INSTANCE;
      }
    
      @Override
      public void windowClosing ( final WindowEvent e ) {
        e.getWindow().dispose();
      }
    }
    

    and with your windows

    window.addWindowListener( ExitListener.getInstance() );
    

    However, be careful in adverse environments, see:
    https://docs.oracle.com/javase/8/docs/api/java/awt/doc-files/AWTThreadIssues.html#Autoshutdown

提交回复
热议问题