gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:13:49 24 4
gpt4 key购买 nike

我正在制作一个带有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com