1

我正在尝试检测 Java 应用程序何时即将关闭,以便我可以执行释放资源的方法,我在 C# 中完成了如下操作:

//Intercept when the application closes
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Reclaim resources from MIDI usage
            if (MIDIControl.CleanUp())
            {
                Logger.Add("Closed resources successfully on Form Close \n");
            }
            else
            {
                Logger.Add("Failed to close all resources on Form Close.");
            }
        }

我尝试在 Java 版本中执行相同的技术,但它似乎不起作用,我尝试调试并且它不会在方法名称上的断点处挂起:

//Intercept when the application closes
        public void windowClosing(WindowEvent we)
        {
            //Reclaim resources from MIDI usage
            if(_midiInstance.CleanUp())
            {
                Logger.Add("Closed resources successfully on ShutDown");
            }
            else
            {
                Logger.Add("Failed to close all resources on ShutDown");
            }
            System.exit(0);
        }

我在等待错误的事件吗?我将如何以与 C# 版本相同的方式执行适当的方法。

谢谢你的时间。

4

1 回答 1

15

您是否已将包含windowClosing()方法的类注册为 via addWindowListener()

除此之外,使用窗口来确定应用程序状态并不是一种好的风格。Java 明确允许您挂钩关闭过程:

Runtime.getRuntime().addShutdownHook(new Thread() {

    @Override
    public void run() {
        // place your code here
    }

});
于 2011-04-20T14:39:35.707 回答