如果你打电话
try {
ImageIO.write(rendered, filetype, new File(file + "." + filetype));
frame.dispose();
logger.trace("Tried to dispose the frame");
} catch (IOException e) {
logger.fatal(e.getMessage());
} finally {
logger.debug("Try to dispose the frame");
frame.dispose();
}
然后代码将被执行,但是
1) 仅当在 EDT 上完成时,否则...... EDT 之外Top-Level Containers
的内容会粘在屏幕上
或者
2)Top-Level Containers
错过的方法finalize()
,然后永远不会GC'ed
(基于来自Windows NT/2000
那个活着的资源的一些限制......),然后来自控制台的输出是正确的并且保持不变,直到当前的JVM实例在那里存在
3) 仅创建一个JFrame
并将此容器重新用于另一个用户操作
编辑
您可以测试 DefaultCloseOperations 和 JFrame#dispose() 的其余设置
您在此处发布的代码与此代码中的 JMenuItem 相同
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.EmptyBorder;
public class ClosingFrame extends JFrame {
private JMenuBar MenuBar = new JMenuBar();
private JFrame frame = new JFrame();
private static final long serialVersionUID = 1L;
private JMenu File = new JMenu("File");
private JMenuItem Exit = new JMenuItem("Exit");
private JFrame frame1 = new JFrame();
public ClosingFrame() {
File.add(Exit);
MenuBar.add(File);
Exit.setBorder(new EmptyBorder(10, 10, 10, 10));
Exit.addActionListener(new ExitListener());
WindowListener exitListener = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == 0) {
System.exit(1);
}
}
};
frame.addWindowListener(exitListener);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setJMenuBar(MenuBar);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
frame1.addWindowListener(exitListener);
frame1.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame1.setPreferredSize(new Dimension(400, 300));
frame1.setLocation(500, 100);
frame1.pack();
frame1.setVisible(true);
}
private class ExitListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
/*JOptionPane.showMessageDialog(null, "Whatever", "Whatever",
JOptionPane.ERROR_MESSAGE);
int confirm1 = JOptionPane.showOptionDialog(frame1,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);*/
if (confirm == 0) {
frame.dispose();
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ClosingFrame cf = new ClosingFrame();
}
});
}
}
编辑 2
在当前 API 的实现中没有任何区别
JFrame#dispose();
和
JFrame#setVisible(false);
也不影响UsedMemory
from current JVM instance
,这个/这些容器会留在内存中,直到当前的 JVM 实例存在