英文:
How can I call a function at time of closing of JFrame?
问题
我想在程序关闭之前进行备份。当用户单击 JFrame 上的(右上角的关闭按钮)时,如何调用备份函数以及在备份后希望窗口被销毁系统退出。我已经设置了默认的关闭操作setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
。
英文:
As i want to go for backup before the closing of program.<br>How i can call backup function when user click on (Right corner button of closing that JFrame) button closing over a JFrame? and after back i wants to be frame get disposed system get exited.<br><br> I have setted default closing Operation setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
答案1
得分: 2
- 将默认关闭操作设置为:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- 向您的窗口添加一个新的
WindowAdapter
,并覆盖(钩住)其windowClosing
方法,如下所示:
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
// 在这里添加您的逻辑
}
});
还要记得在完成后手动销毁窗口,并调用 System#exit
以关闭应用程序。
更多信息请参阅相关文档:
https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/event/WindowAdapter.html
英文:
Very simply by doing the following:
- Setting the default close operation to:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- Adding a new
WindowAdapter
to your frame and override (hooking) on itswindowClosing
method like so:
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
//your logic here
}
});
Also don't forget that you will need to manually dispose the frame as well as call System#exit
once done in order to close the application.
For more check the related documentation here:
https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/event/WindowAdapter.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论