I started writing a small program to learn a bit more about java and try to design my layouts by hand without always using NetBeans.
Thing is, when I run my project and close it, it won’t stop running in NetBeans, so everytime I re-run it creates another run. By searching and looking at another GUI I had created using NetBeans I thought adding the
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
would do the trick, but I guess I am wrong.
Can someone please explain me what I should do?
Here is a SSCCE of my programa: http://pastebin.com/QhKpwdDw
Thank you very much in advance!
You might want to take a look at this question: How to close a Java Swing application from the code, as it deals with closing the application in general and also how to ensure it completely terminated.
But to answer your question quickly, there are a couple of options.
Option 1
Since you are extending
JFramein your class, you can just useEXIT_ON_CLOSEto quit.NOTE:
EXIT_ON_CLOSEexits allJFramesin your application, not just the one it is applied to.Option 2
This is most likely not the answer you want, but
DISPOSE_ON_CLOSEwill close only theJFrameyou are applying it to.If you have multiple
JFramesopen, or if you have any otherThreads, they will keep running and the program will not end. But if you only have oneThreadand oneJFrame, this will close the application.My Preference
I would go with Option 1, disagreeing with everyone else. It is directly tied to
JFrameand not dependent onWindowConstants, which makes things cleaner and more reliable. But more importantly, it closes all of the windows, not just the one that you apply it to.Even though it looks like you only have one window, you may have other internal
Threadselsewhere in your program that NetBeans is throwing in there.To be sure everything closes, you want to use
EXIT_ON_CLOSE.Extra Information
For a discussion on how
DISPOSE_ON_CLOSEandEXIT_ON_CLOSEdiffer: http://www.coderanch.com/t/340183/GUI/java/DISPOSE-CLOSE-vs-EXIT-CLOSEDocumentation on
JFrame'sEXIT_ON_CLOSE: http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html#EXIT_ON_CLOSEDocumentation on
DISPOSE_ON_CLOSEand otherWindowConstants: http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/WindowConstants.html#DISPOSE_ON_CLOSE