【问题标题】:Having 2 separate close buttons for 2 JFrames?2 个 JFrame 有 2 个单独的关闭按钮?
【发布时间】:2011-04-29 15:20:23
【问题描述】:

我正在制作一个带有 JMenuBar 的小应用程序,现在,我得到了一个 menuitem,它是一个商店,它打开了一个新的 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);
}

【问题讨论】:

  • 这个没有代码很难回答。猜测的可能性也很大。
  • 好的,但是在这一点上我们仍然看不到他们的代码 menuitem 有问题。

标签: java swing jframe


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您之前是否曾向JFrame.setDefaultCloseOperation 拨打过EXIT_ON_CLOSE 之类的电话?尝试将其设置为DO_NOTHING_ON_CLOSE,您可以随意处理关闭事件。

    【讨论】:

    • 好吧,我确实想关闭它,我只是不想关闭整个程序。
    • 或许将其设置为HIDE_ON_CLOSE 或DISPOSE_ON_CLOSE。
    猜你喜欢
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 2019-06-16
    • 2020-05-05
    • 1970-01-01
    相关资源
    最近更新 更多