关闭程序时运行方法?

Sta*_*tan 13 java swing

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

Vic*_*kin 30

添加关闭钩子.看到这个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"));
}
Run Code Online (Sandbox Code Playgroud)


bra*_*boy 7

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

这是代码

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

}
Run Code Online (Sandbox Code Playgroud)

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

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