我试图检测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#版本相同的方式执行适当的方法。
谢谢你的时间。
最佳答案
您是否已通过windowClosing()
注册了包含addWindowListener()
方法的类?
除此之外,使用窗口来确定应用程序状态不是一种好的样式。 Java明确允许您挂钩关闭过程:
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// place your code here
}
});