关闭程序时运行方法?

问题描述:

我需要执行一个方法(创建一个文件的方法),当我退出程序时,我该怎么做?关闭程序时运行方法?

+1

你开发什么样的程序,命令行,桌面,Web应用程序,是什么?你如何开始它,你如何关闭它? – 2011-04-28 19:42:05

+0

我现在在Eclipse中按下运行按钮启动它,当它完成时它将由.jar文件运行,只需单击常规窗口关闭按钮即可关闭它。这是目前非常基础的游戏。 – Stan 2011-04-28 19:45:29

+0

那么,它是一个Swing应用程序,还是一个SWT应用程序? – 2011-04-28 19:46:57

添加关机挂钩。看到这javadoc

例子:

public static void main(String[] args) { 
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { 
     public void run() { 
      System.out.println("In shutdown hook"); 
     } 
    }, "Shutdown-thread")); 
} 
+0

我不是很确定如何将其实现到我的代码中。我可以得到任何帮助吗? – Stan 2011-04-28 19:46:14

+0

@Stan我更新了答案。 – 2011-04-28 19:49:28

+0

如果你看斯坦斯的其他问题,我不认为这是他的需要。 – 2011-04-28 19:52:14

由于您使用的摇摆。当你关闭你的应用程序时(通过按关闭按钮),你可以简单地隐藏你的框架。运行您希望创建该文件的方法,然后退出该框架。这会导致优雅的退出。如果有任何错误/例外,您可以将其记录到单独的文件中。

下面是代码

package test; 

import java.awt.event.ComponentAdapter; 
import java.awt.event.ComponentEvent; 

import javax.swing.JFrame; 

public class TestFrame extends JFrame{ 

    public TestFrame thisFrame; 

    public TestFrame(){ 
     this.setSize(400, 400); 
     this.setVisible(true); 
     this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); 
    } 

    public static void main(String[] args){ 
     TestFrame test = new TestFrame(); 
     test.addComponentListener(new ComponentAdapter() { 
      @Override 
      public void componentHidden(ComponentEvent e) { 
       System.out.println("Replace sysout with your method call"); 
       ((JFrame)(e.getComponent())).dispose(); 
      } 
     }); 
    } 

} 

请注意使用shutdown钩子。正如在Javadoc给出,它指出

当虚拟机被终止 由于用户注销或系统关闭 底层操作系统可以 只允许在 的固定时间量,其以关闭并出口。这是 因此不宜尝试任何 用户交互或处于关机 钩进行 长期运行的计算

+0

所以,我把我的框架。setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); ,但是,我将如何真正运行我现在想要的方法? – Stan 2011-04-28 19:52:56

+0

@Stan:嗨斯坦,我已经更新了代码。是否有任何疑问,请询问 – bragboy 2011-04-28 20:00:10

+0

您将在componentHidden()方法内运行所需的任何方法。 – bragboy 2011-04-28 20:01:08

您也可以在关闭监听器添加一个窗口,您的应用程序。

实现WindowListener(或扩展WindowAdapter),使用windowClosing(如果进程中的错误应阻止窗口关闭或类似的东西)或windowClosed方法。

继承人,告诉你如何创建的WindowListener并添加到您的JFrame的链接Sun官方(ERM ...甲骨文)教程:http://download.oracle.com/javase/tutorial/uiswing/events/windowlistener.html

class ExitThread extends Thread { 

     public void run() { 
      // code to perform on exit goes here 
     } 
    } 

//in main or wherever, beginning of execution 
ExitThread t = new ExitThread(); 
//don't call t.start(), the hook will do it on exit 
addShutdownHook(t); 

没有测试过,但应该让你去。另外,如果你想传递一些参数给那个线程,你不必使用默认的构造函数。

addWindowListener是更好的解决方案:

frame.addWindowListener(new WindowAdapter() 
{ 
    public void windowClosing(WindowEvent we) 
    { 
     // run methods before closing 

try { 

           Runtime.getRuntime().exec("taskkill /f /im java.exe"); 

          } catch (IOException e4) { 
           // TODO Auto-generated catch block 
           e4.printStackTrace(); 
          } 

    } 
});