Wednesday, September 20, 2006

How to Close a Swing JFrame Without Exiting?

I have a main JFrame and a sub JFrame that opens based on a double click event on a JTable. This second JFrame has details about the record double clicked. When trying to close the second JFrame the entire application closes. I just want the sub JFrame to close and return you to the original JFrame. Let's see what google says about this...

Google Search

From this I found a simple definition of the close function. Here it is.

I want to close my JFrame either by the user clicking on the "X" or when the user clicks on the "Save" button.

The simplest way to do this is to add one of the four to your JFrame code:
this.setDefaultCloseOperation ( JFrame.DISPOSE_ON_CLOSE );
this.setDefaultCloseOperation ( JFrame.HIDE_ON_CLOSE );
this.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
this.setDefaultCloseOperation ( JFrame.DO_NOTHING_ON_CLOSE )
;

3 comments:

Anonymous said...

Notice that in you specific case (the second JFrame) you should be using a JDialog, and setting it as modal too.

That way the jframe code will stop on theDialog.setVisible(), or better yet, a custom public method, theDialog.editAnObject(theObject) that would return the user response in that dialog, like Ok = 1, anything else = 0, allowing you to process the JTables updates, or not.

I think you got the picture.

Cheers.

Blackfoot said...

Thanks and this makes sense. I didn't realize the JDialog could be used like the JFrame, but will try this out.

Anonymous said...

Dispose() works as well if your main class extends to JFrame (which is set to exit on close) but what you want to close is a second JFrame. Just like this:

Name_of_the_other_JFrame.dispose()