java - 2 个 JFrames 有 2 个单独的关闭按钮?

标签 java swing jframe

我正在制作一个带有 JMenuBar 的小型应用程序,现在,我得到了一个菜单项,它是一个商店,它打开了一个新的 JFrame。当我单击该按钮时,会出现一个新的 JFrame,一切正常。但是,当我单击 Store JFrame 的关闭按钮时,我不想关闭主 JFrame。如果我现在按下商店关闭按钮,它将同时关闭主 JFrame 和商店 JFrame,这对为这 2 个 JFrame 制作 2 个单独的关闭按钮有什么帮助吗?主 JFrame 的代码:

    public static void main(String[] args){

    //Create new JFrame
    JFrame frame = new JFrame();
    frame.setTitle("MrStan");
    frame.setSize(200, 200);
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.setJMenuBar(menubar);

    //Set location of JFrame
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    int screenWidth = (int) dim.getWidth();
    int screenHeight = (int) dim.getHeight();
    frame.setLocation(screenWidth / 2 - 200, screenHeight / 2 - 200);

    //Set ContentPane to JPanel
    MrStan panel = new MrStan();
    frame.setContentPane(panel);

    //Make the user not be able to resize
    frame.setResizable(false);

    //Make the JFrame visible
    frame.setVisible(true);

}

我的商店 JFrame:

    public MrStanStore(){   
    JFrame frame2 = new JFrame();
    frame2.setTitle("Store");
    frame2.setSize(300, 200);
    frame2.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    //Set location of JFrame
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    int screenWidth = (int) dim.getWidth();
    int screenHeight = (int) dim.getHeight();
    frame2.setLocation(screenWidth / 2 - 200, screenHeight / 2 - 200);

    //Make the user not be able to resize
    frame2.setResizable(false);

    //Make the JFrame visible
    frame2.setVisible(true);
}

最佳答案

不要使用 2 个 JFrame。通常,应用程序应该有一个 JFrame,然后使用 JDialogs 来支持窗口。 JDialogs 不支持在关闭时退出 VM,因此这不会成为问题。

如果您确实使用了 JFrame,那么您应该使用 DISPOSE_ON_CLOSE。然后当最后一帧关闭时,VM 将自动退出。

关于java - 2 个 JFrames 有 2 个单独的关闭按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5833935/

相关文章:

java - 在 ListView JavaFX中显示sql查询结果

java - 只想提取$$text$$

java - Android PDF 加载时序

java - 自定义 JPanel 在第二个自定义 JPanel 中导致呈现问题

java - JFrame 窗口不显示

java - 不推荐使用 WebMvcConfigurerAdapter 类型

Java Swing : How to invoke stopCellEditing() before TreeListeners:valueChanged?

java - Graphics2D 是后现代的

java - 最大化 JFrame 窗口的不同方式?

java - JPanel 组件在尝试刷新后消失