检测Java应用程序何时关闭

我试图检测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#版本相同的方式执行适当的方法。

谢谢你的时间。

您是否通过addWindowListener()注册了包含windowClosing()方法的类?

除了使用窗口来确定应用程序状态不是一个好的风格。 Java明确允许您挂钩关闭进程:

 Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { // place your code here } }); 
    Interesting Posts