你可以在 JFrame 关闭时调用一个函数。

huangapple go评论77阅读模式
英文:

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

  1. 将默认关闭操作设置为:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

  1. 向您的窗口添加一个新的 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:

  1. Setting the default close operation to:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

  1. Adding a new WindowAdapter to your frame and override (hooking) on its windowClosing 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

huangapple
  • 本文由 发表于 2020年8月7日 01:02:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63288478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定