问题是,当一个 JFrame 关闭时,另一个 JFrame 是否可以自动打开。如 cmets 中所述,两种可能的常见解决方案包括使用 WindowListener 或使用模式对话框(其中一个示例是 Chance Hoard 提到的 JOptionPane,它也是 one 解决方案,但肯定不是唯一的解决方案)。
要使 WindowListener 工作,您可以在 windowClosed() 方法中打开新的 JFrame,例如:
JFrame frame1 = new JFrame("Frame 1");
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.add(Box.createRigidArea(new Dimension(500, 400)));
frame1.pack();
frame1.setLocationByPlatform(true);
frame1.setVisible(true);
frame1.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
JFrame frame2 = new JFrame("Frame 2");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.add(Box.createRigidArea(new Dimension(500, 400)));
frame2.pack();
frame2.setLocationByPlatform(true);
frame2.setVisible(true);
}
});
这里的关键是将默认关闭操作设置为不是JFrame.EXIT_ON_CLOSE,以免在初始JFrame窗口关闭后关闭JVM。在窗口监听器的windowClosed() 方法中,创建并显示第二个JFrame。
为了使用模态对话框解决这个问题,我将创建第二个窗口,它可能是一个 JFrame,首先,给对话框一个父应用程序,然后我会编写代码来显示它之后 显示模式对话框。这样,它只会在对话框不再可见时显示:
JFrame frame3 = new JFrame("Frame 3");
frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame3.add(Box.createRigidArea(new Dimension(500, 400)));
frame3.pack();
frame3.setLocationByPlatform(true);
// don't display this JFrame yet
// create the dialog, passing in the JFrame and making the dialog "modal"
JDialog dialog1 = new JDialog(frame3, "Dialog 1", ModalityType.APPLICATION_MODAL);
dialog1.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog1.add(Box.createRigidArea(new Dimension(500, 400)));
dialog1.pack();
dialog1.setLocationRelativeTo(frame3);
// show the dialog first
dialog1.setVisible(true);
// this is called only after the dialog is no longer visible
frame3.setVisible(true);
说了这么多,我仍然建议您阅读The Use of Multiple JFrames, Good/Bad Practice? 链接,我建议避免两种上述“解决方案”,而是建议创建并显示单个主应用程序窗口,一个 JFrame,而是使用 CardLayout 交换 GUI views,通常是 JPanel。