简体   繁体   English

关闭主JFrame

[英]Closing the Main JFrame

I have a main jFrame with the help of which i press button and open new JFrames but the problem is that when i open other JFrame the previous ones still remains there where as what i want is that when i press next button then i move forward to the new JFrame (the previous one should not be there) and when i press previous button i move back to the previous JFrame. 我有一个主jFrame,可以通过它按下按钮并打开新的JFrames来解决,但问题是当我打开其他JFrame时,先前的JFrame仍然保留在那里,因为我想要的是当我按下next按钮时,我继续前进新的JFrame(上一个不应存在),当我按上一个按钮时,我将移回上一个JFrame。

I know there are functions of dispose,they do well like jframe1.dispose() but i dont get it how to hide the very first JFrame whose code in the main is written like this 我知道有一些dispose函数,它们和jframe1.dispose()一样好,但是我不知道如何隐藏第一个JFrame,其代码在主体中是这样写的

    public static void main(String args[]) {


    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() 
          {          
           new GraphicalInterface().setVisible(true);
          }
       });
     }

how do i set this as .setVisible(false) in the button code? 如何在按钮代码中将此设置为.setVisible(false)?

You need to retain a reference to the JFrame , so you can set it's visibility later. 您需要保留对JFrame的引用,以便稍后设置它的可见性。

private JFrame myFrame;

public void run() {
  myFrame = new GUI();
  myFrame.setVisible(true);
}

public void hide() {
  myFrame.setVisible(false);
}

Note that a JFrame is a top-level container, you are only really supposed to have one per application. 请注意, JFrame是顶级容器,实际上每个应用程序只应具有一个。 It may be better if instead of using multiple JFrame s you use just one, and swap in various JPanel s instead. 如果不使用多个JFrame而是只使用一个,然后交换各种JPanel可能会更好。

It would safe resources if you keep just one frame and set a new panel as content. 如果只保留一帧并设置一个新面板作为内容,则将确保资源的安全。

Your question was how to handle the reference to the frame? 您的问题是如何处理对框架的引用? Please provide the code where the next frame is created. 请提供创建下一帧的代码。

You could assign your GUI (extends JFrame I suppose) to a variable and call .setVisible(false) on that object. 您可以将您的GUI(我想扩展JFrame)分配给一个变量,然后对该对象调用.setVisible(false)。 Since your object from the code above is more or less anonymous, you won't have access on that. 由于上面代码中的对象或多或少是匿名的,因此您将无权访问。

You could also check this . 您也可以检查一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM