这里是 Java 菜鸟。当用户按下 Windows 关闭按钮时,扩展 JDialog 的 Swing 类不会释放 - java.exe 保留在内存中。我已经将代码直接剥离到这个 shell,但我仍然得到这种行为。
我查看了其他示例,例如 Basic Java Swing, how to exit and dispose of your application/JFrame
当我注释掉该示例代码中的两行 System.exit(0)
行时,该示例中的类仍然正确处理。我缺少什么让我的类(class)处理掉?
import javax.swing.JFrame;
import javax.swing.JDialog;
public class WhyNoDispose extends JDialog{
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
WhyNoDispose frame = new WhyNoDispose("my title");
frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
frame.setVisible(true);
//System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public WhyNoDispose(String title) {
super(new JFrame(title), ModalityType.APPLICATION_MODAL);
pack();
}
}
最佳答案
您正在创建一个 JFrame 并且从未在此处处置它:
public WhyNoDispose(String title) {
super(new JFrame(title), ModalityType.APPLICATION_MODAL); // *********
pack();
}
因此,由于 JFrame 处于 Activity 状态并且 GUI 已呈现,Swing 事件线程将继续运行。
如果您使 JFrame 的行为使程序在 JFrame 关闭时退出,然后显式处置 JFrame,您的程序现在将退出:
import java.awt.Window;
import javax.swing.JFrame;
import javax.swing.JDialog;
public class WhyNoDispose extends JDialog {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
WhyNoDispose frame = new WhyNoDispose("my title");
frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
JFrame win = (JFrame) frame.getOwner();
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
win.dispose();
// System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public WhyNoDispose(String title) {
super(new JFrame(title), ModalityType.APPLICATION_MODAL);
pack();
}
}
但是,至少可以说,这是非常困惑的代码——如果拥有的窗口不是 JFrame 怎么办?如果为空怎么办?
另一个解决方案是根本不使用 JFrame,这样当 JDialog 被释放时,就没有留下持久窗口来使事件线程持久化:
import java.awt.Window;
import javax.swing.JFrame;
import javax.swing.JDialog;
public class WhyNoDispose extends JDialog {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
WhyNoDispose frame = new WhyNoDispose("my title");
frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public WhyNoDispose(String title) {
super((JFrame)null, title);
pack();
}
}
关于Java 对话框不释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22851542/