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

Kevin picture Kevin · Jan 17, 2011 · Viewed 72.6k times · Source

My program starts with a picture with a textfield in a JFrame. I want when the user types start it closes the picture JFrame and opens another JFrame with the main program. I've tried

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

on the Image frame but it closes all the windows.

Answer

AniDev picture AniDev · Jan 17, 2011

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.