2011-10-26 37 views
2

这是一个“最佳实践”类型的问题。 AFAIK有两种方法(可能还有更多的..)需要事先到JVM停止执行任务时:如何确保在关闭Java桌面应用程序后执行任务?

  1. 添加WindowListener到容器和覆盖windowClosing事件
  2. 添加一个关闭挂钩(即Runtime.addShutdownHook

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

+0

我的问题你真的想知道什么,v for v + 1怪异的问题 – mKorbel

回答

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

不要使用神奇的数字! 0代表是或否? – camickr

+0

@camickr纠正我的错误习惯之一 – mKorbel

相关问题