关闭程序时运行方法?

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

添加关机钩子。 看到这个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")); } 

因为你正在使用Swing。 当您关闭应用程序时(通过按关闭按钮),您可以简单地隐藏您的框架。 运行您想要的创建文件的方法,然后退出框架。 这将导致优雅的退出。 如果有任何错误/exception,您可以将其记录到单独的文件中。

这是代码

 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(); } }); } } 

请注意使用关机挂钩。 正如Javadoc所述 ,它表明了这一点

当虚拟机因用户注销或系统关闭而终止时,底层操作系统可能只允许一段固定的时间来关闭和退出。 因此,不建议尝试任何用户交互或在关闭钩子中执行长时间运行的计算

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

下面是官方Sun(Erm … Oracle)教程的链接,该教程告诉您如何创建WindowListener并将其添加到JFrame: 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(); } } });