如何在Java Swing中为窗口关闭创建处理程序 [英] How to create a handler for window closing in Java Swing

查看:216
本文介绍了如何在Java Swing中为窗口关闭创建处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的窗口(使用Java Swing创建)关闭时,我正在尝试调用一个函数来进行清理。
在我的初始化代码中,我这样做:

I'm trying to call a function to do cleanup when my window (created with Java Swing) is closed . In my initialization code I do this:

public class FormLogin extends JFrame{
    private void initComponents(){
        ...
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt){
                formLoginWindowClosed(evt);
            }
        });
        ...
    }
}

但功能当我按下退出按钮时,永远不会调用formLoginWindowClosed。我也尝试用java.awt.event.WindowAdapter作为参数创建监听器,但它也不起作用。
我应该如何为窗口关闭创建监听器?
提前致谢。

But the function "formLoginWindowClosed" is never called when I press the exit button. I've also tried creating the listener with java.awt.event.WindowAdapter as an argument, but it didn't work either. How should I create the listener for window closing? Thanks in advance.

推荐答案

将框架设置为关闭时退出, windowClosed <永远不会调用/ code>,主要是因为系统在事件发生之前已经退出。

With the frame set to exit on close, windowClosed will never be called, mostly because the system has already exited before the event can be raised.

尝试使用 windowClosing 而不是。

或者,您可以使用 关闭钩子

Alternatively, you could use a shut down hook

  • JVM Shutdown Hook in Java
  • Design of the Shutdown Hooks API
  • Java Shutdown hook – Runtime.addShutdownHook()

这篇关于如何在Java Swing中为窗口关闭创建处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆