Wnen I use external resources such as files or DB connection I need to close them before I let them go.
Do I need to do the same thing with Swing components ? If yes then how ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Normally, you don’t need to dispose of objects when you are done with them (although setting the references to them to null may allow them to be GCed sooner). However, AWT and Swing objects allocate some amount of native resources that need to be freed. Furthermore, the AWT thread treats the windows as top-level objects, preventing them from being garbage collected and the JVM from terminating.
Thus, when you are done with your window, you need to dispose of it, which frees the native resources that it has allocated. One way to do this is to call Window.dispose() on it. However, a better option would be to call JFrame.setDefaultCloseOperation() when you initialize each of your root windows. If you pass it DISPOSE_ON_CLOSE it will take care of disposing itself when the user closes the window. When the last such window closes, the AWT thread will stop blocking and allow the JVM to close (assuming you don’t have any other aberrant threads running). Alternatively, you can pass it EXIT_ON_CLOSE, which will cause your window to call System.exit(), which tells the JVM that your application is done and to gracefully terminate.