Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic close of JFrame

Tags:

java

swing

jframe

What's the programmatic equivalent of clicking the close (x) button in the upper right corner of a JFrame?

There's the dispose() method but that's not the same thing, since a JFrame can be set to do several different things upon closing (not to mention if there's a WindowListener involved)

like image 851
Jason S Avatar asked Oct 08 '10 16:10

Jason S


People also ask

Which method is used to close a Swing frame?

We can close the AWT Window or Frame by calling dispose() or System. exit() inside windowClosing() method. The windowClosing() method is found in WindowListener interface and WindowAdapter class.

How do you close a JFrame when another opens?

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.

How do I close a JFrame without exiting?

Use anything for setDefaultCloseOperation excepting EXIT_ON_CLOSE . Then, for the cancel button, just dispose() the window. If the application has another running thread, it won't exit. You can also hide a window by calling setVisible(false) .


1 Answers

You tell the component to dispatch an event. In this case, you want it do dispatch a Window Closing event.

private void exit() {
    this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
like image 61
jjnguy Avatar answered Sep 19 '22 16:09

jjnguy