user1508381
user1508381

Reputation:

How to actually close a Window in Java?

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?

Upvotes: 0

Views: 538

Answers (4)

Duncan Jones
Duncan Jones

Reputation: 69329

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.

Upvotes: 1

nullpotent
nullpotent

Reputation: 9260

frame.dispose();
frame = null; 

Upvotes: 0

Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

When the user pressed the "X-button"? In that case use

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Upvotes: 1

DWolf
DWolf

Reputation: 725

 Frame.dispose() or setVisible(false)

Upvotes: 1

Related Questions