Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFrame Exit on close Java

Tags:

java

jframe

I don't get how can I employ this code:

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

to close the program with the x button.

like image 328
user983246 Avatar asked Oct 17 '11 21:10

user983246


People also ask

What is JFrame exit on close?

EXIT_ON_CLOSE is that once all the jframes are closed, it basically calls a System. exit(0) which means it kills all other outstanding threads!

How do you exit a JFrame?

You can easily close your JFrame by clicking on the X(cross) in the upper right corner of the JFrame. However JFrame. setDefaultCloseOperation(int) is a method provided by JFrame class, you can set the operation that will happen when the user clicks the X(cross).

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) .


2 Answers

You need the line

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 

Because the default behaviour for the JFrame when you press the X button is the equivalent to

frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); 

So almost all the times you'll need to add that line manually when creating your JFrame

I am currently referring to constants in WindowConstants like WindowConstants.EXIT_ON_CLOSE instead of the same constants declared directly in JFrame as the prior reflect better the intent.

like image 132
Jaime Hablutzel Avatar answered Sep 20 '22 13:09

Jaime Hablutzel


If you don't have it, the JFrame will just be disposed. The frame will close, but the app will continue to run.

like image 25
Jeff Storey Avatar answered Sep 23 '22 13:09

Jeff Storey