I don't get how can I employ this code:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
to close the program with the x button.
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!
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).
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) .
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.
If you don't have it, the JFrame will just be disposed. The frame will close, but the app will continue to run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With