Java: How do I close a JFrame while opening another one?

Solution 1:

The method JFrame.setVisible can be used to hide or display the JFrame based on the arguments, while JFrame.dispose will actually "destroy" the frame, by closing it and freeing up resources that it used. Here, you would call setVisible(false) on the picture frame if you intend to reopen it, or call dispose() on the picture frame if you will not be opening it again, so your program can free some memory. Then you would call setVisible(true) on the main frame to make it visible.

Solution 2:

you also can use this code

for example

  JFrame frame = new JFrame();
  frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

Solution 3:

Maybe if you set the picture JFrame's default close operation to something besides EXIT_ON_CLOSE, perhaps DISPOSE_ON_CLOSE, you can prevent your application from closing before the second JFrame appears.

Solution 4:

This post is a bit old but nevertheless.

If you initialize the form like that:

JFrame firstForm = new JFrame();

firstForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
firstForm.setSize(800, 600);
firstForm.setLocationRelativeTo(null);

firstForm.setVisible(true);

And for instance create or open another form by a button:

JFrame secondForm = new JFrame();

secondForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
secondForm.setSize(800, 600);
secondForm.setLocationRelativeTo(null);

secondForm.setVisible(true);

this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));

This will dispose and destroy the first window without exiting the program.
The key is to set setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE).
It also raises the events (I've tested it with the WindowClosing event).

Solution 5:

Here is my solution to this problem:

public void actionPerformed(ActionEvent e) {
    String userName =  textField.getText();
    String password = textField_1.getText();
    if(userName.equals("mgm") &&  password.equals("12345")) {            
         secondFrame nF = new secondFrame();

         nF.setVisible(false);
         dispose();          
    }   
    else 
    {
        JOptionPane.showMessageDialog(null, " Wrong password ");
    }
}