有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing如何确保在关闭Java桌面应用程序时执行任务?

这是一个“最佳实践”类型的问题。AFAIK有两种方法(可能更多)当需要在JVM关闭之前执行任务时:

  1. WindowListener添加到容器并重写windowClosing事件
  2. 添加一个关闭挂钩(即^{}

对于Java桌面应用程序,哪种方法是“首选”方法?有“首选”方式吗


共 (1) 个答案

  1. # 1 楼答案

    不是最佳实践,不是首选方式,只是关闭当前JVM实例,非常简单

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

    2)添加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是如何显示来自另一个新JVM实例的错误消息的休止符