Java WindowClosing event not called when jFrame.setUndecorated(true) is set

会有一股神秘感。 提交于 2019-12-24 22:23:19

问题


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);

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);
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/57257529/java-windowclosing-event-not-called-when-jframe-setundecoratedtrue-is-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!