How to go back to a JFrames in Java

前端 未结 3 1533
别跟我提以往
别跟我提以往 2021-01-06 06:45

I have a button in a JFrame, if pressed, it takes us to another frame. I used this code:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt         


        
3条回答
  •  梦谈多话
    2021-01-06 07:13

    For swing applications, the standard is to use a STATIC MAIN FRAME, in other words, make your main frame (mframe) static and add methods to pop-up new frames, dialogs, optionPanes, etc. You can even control the visibility of the main frame throw static calls. That's the way you implement a UNIQUE FRAME for your application, even tho you instance other frames for navigation, all child frames can refer to the main frame without the need of passing it as parameter to constructors or creating new instances of it.

    The Main Class

    `/* to start the application */

    public class Main{
        public static MainFrame MFRAME;
    
        public static void main(String[] args){
            /*use this for thread safe*/
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    Main.MFRAME = new MainFrame(/*init parms to constructor*/);
                }
            });
        }
    }
    

    `

    The Main Frame

    `/* to create the main frame */

    public class MainFrame extends JFrame{
    
        public MainFrame(/*your constructor parms*/){
            /* constructor implementation */
        }
    
    
        public void openOtherFrame(/*your parms*/){
            OtherFrame oFrm = new OtherFrame(/*your parms*/);
        }
    
        /* other methods implementation */
    }
    

    `

    The child frame

    `/* to open child frames controling the visibility of the main frame*/

    public class OtherFrame extends JFrame{
    
        public OtherFrame(/*your constructor parms*/){
            /* hide main frame and show this one*/
            Main.MFRAME.setVisible(false);
            this.setVilible(true);
            /* do something else */
            /* show main frame and dispose this one*/
            Main.MFRAME.setVisible(true);
            this.dispose();
        }
    
        /* other methods implementation */
    }
    

    `

提交回复
热议问题