问题
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