【问题标题】:Make the X Close button open a new JFrame in Java使 X 关闭按钮在 Java 中打开一个新的 JFrame
【发布时间】:2022-01-06 00:22:48
【问题描述】:

我想这样当你点击右上角的 X 关闭按钮时,会出现一个新的JFrame,并关闭当前的JFrame

我该怎么做?

【问题讨论】:

  • 查找WindowListener。您可能想查找 DefaultCloseOperation
  • 或者使用模态JDialog。但不管你走哪条路,先请阅读The Use of Multiple JFrames, Good/Bad Practice?
  • @MadProgrammer 你能告诉我如何使用窗口监听器吗?我无法让它工作。例如:@Override public void windowOpened(WindowEvent e) { System.out.println("Hello world"); }(我知道它是 @Override 没有空格,但我不能那样输入,因为我已经提到过你)
  • 请注意,用户通常会因为想要退出而关闭窗口。拒绝让用户离开可能会让他们非常恼火。
  • @Hilex23 请花时间研究你的问题,从How to Write Window ListenersJavaDocs 开始,尝试一些事情,如果你仍然没有得到你期望的结果,发布带有minimal reproducible example 的新问题展示了您的尝试

标签: java swing jframe


【解决方案1】:

问题是,当一个 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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多