JFrame Exit on close Java

user983246 picture user983246 · Oct 17, 2011 · Viewed 193.2k times · Source

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

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

to close the program with the x button.

Answer

Jaime Hablutzel picture Jaime Hablutzel · Oct 17, 2011

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.