设置jFrame.setUndecorated(true)时未调用Java WindowClosing事件 [英] Java WindowClosing event not called when jFrame.setUndecorated(true) is set

查看:129
本文介绍了设置jFrame.setUndecorated(true)时未调用Java WindowClosing事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码段中,除非您删除该代码段的一行代码,否则不会调用WindowClosing事件. 要删除的代码行是:

In the following snippet the WindowClosing event is not called except if you remove one line of code to the snippet. The line of code to be removed is:

jFrame.setUndecorated(true);

显然,此setUndecorated(true)方法禁用WindowListener/WindowAdapter功能.这正常吗?

Apparently this setUndecorated(true) method disables the WindowListener/WindowAdapter functionality. Is this normal?

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.HeadlessException;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.commons.io.FileUtils;

public class WindowClosing extends JFrame {

    private static WindowClosing jFrame;
    private static Container contentPane;

    public WindowClosing() throws HeadlessException {
        super();
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    JOptionPane.showMessageDialog(null, "closing" ,"Cookie", JOptionPane.INFORMATION_MESSAGE);
                    try {
                        FileUtils.cleanDirectory(new File("./temp/"));
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    e.getWindow().dispose();
                    System.exit(0);
                    }
            });
    }

    public static void main(String[] args)  {
        jFrame = new WindowClosing();
        jFrame.setUndecorated(true);
        jFrame.pack();
        contentPane = jFrame.getContentPane();
        contentPane.setLayout(new BorderLayout());
        jFrame.setVisible(true);
    }
}

推荐答案

关闭框架时未调用WindowListener的原因是: 窗口未通过框架的关闭图标关闭,该图标已被jFrame.setUndecorated(true);禁用. 即使存在系统图标(关闭,最大化,最小化),并且用户使用菜单项关闭框架,也不会调用WindowListener.

The reason WindowListener is not called when closing the frame is due to: the window is not closed with the closing icon of the frame, which are disabled by jFrame.setUndecorated(true);. Even if the system icons (close, maximize, minimize) are present and the user close the frame with a menu item, the WindowListener is not called.

这篇关于设置jFrame.setUndecorated(true)时未调用Java WindowClosing事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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