I need to close a JFrame
window so that the next call to access it catches NullPointerException
.I tried frame.dispose()
but, it did not work, I am getting back that window whenever I try frame.setVisible(true)
. How can I do that?
Asked
Active
Viewed 528 times
0

Andrew Thompson
- 168,117
- 40
- 217
- 433
-
Check this link out for some reference material: http://stackoverflow.com/questions/1234912/how-to-programmatically-close-a-jframe – Grambot Nov 09 '12 at 14:54
-
The code is too big to post here. – Nov 09 '12 at 15:07
-
*"I need to close a JFrame window so that the next call to access it"* There should only be one `JFrame` and it should be visible form application start to finish (unless the user minimizes it or brings other apps. in front of it). See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson Nov 09 '12 at 22:19
4 Answers
1
I suggest you re-evaluate your program logic as it seems strange that you would rather see a NullPointerException
instead of just knowing your code won't try and make visible a frame that should be dead.
Regardless, you can simply set your JFrame
instance to null
to ensure it cannot be made visible again. That will certainly give you the exception you desire.
Remember that a NullPointerException
should be reserved for indicating programming errors, typically the violation of an API contract. Don't use them to control program flow, nor design a program that is knowingly going to trigger them.

Duncan Jones
- 67,400
- 29
- 193
- 254
-
Actually, I have already wrote a large program (with some catch of `NullPointerException`'s), if I could do that then I will not need to modify my code a lot. – Nov 09 '12 at 15:06
1
When the user pressed the "X-button"? In that case use
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Tobias Moe Thorstensen
- 8,861
- 16
- 75
- 143
-
1That would end the application. Use `JFrame.DISPOSE_ON_CLOSE` instead. – Andrew Thompson Nov 09 '12 at 22:20