【问题标题】:How to ensure a task is executed upon closing a Java Desktop Application? [closed]如何确保在关闭 Java 桌面应用程序时执行任务? [关闭]
【发布时间】:2011-10-26 13:31:50
【问题描述】:

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

  1. 将WindowListener 添加到容器并覆盖windowClosing 事件
  2. 添加关闭挂钩(即Runtime.addShutdownHook)

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

【问题讨论】:

  • 我的问题你真的想知道什么,+1 非常奇怪的问题

标签: java swing


【解决方案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 实例的错误消息

【讨论】:

  • 不要使用幻数! 0 表示是或否?
  • @camickr 是我的错误习惯之一
猜你喜欢
  • 2011-02-15
  • 2011-08-04
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 2012-12-12
相关资源
最近更新 更多