JOptionPane preventing program from ending
I wanted to use a JOptionPane to display a simple message. And it all appears to work fine. But the program never ends. Its not stuck in any obvious loops or similar.
See the simple program below that demonstates the problem
Code :
import javax.swing.*;
public class MainScreen {
public static void main(String[] args) {
System.out.println("begin");
JFrame frame = new JFrame("ERROR");
JOptionPane.showMessageDialog(frame,"This is a message");
System.out.println("end");
}
}
From the System.out.println statements it can be seen that after the ok button is pressed it runs to the end. But the program doesn't exit. Im running it in the Netbeans IDE if that makes any difference
The only solution i've found on the internet is to put system.exit(0) at the end of the code. But this seems like it would be bad practice. Leaving some remnant of the JOptionPane hanging around clogging up memory then forcing it to close. Is this in fact how its supposed to be done?
Thanks for any help (I presume i'm missing a simple instruction)
Re: JOptionPane preventing program from ending
You have two things going on here.
1) JOptionPane.showMessageDialog(frame,"This is a message");
2) JFrame frame = new JFrame("ERROR");
Its been a while since I have played with JOptionPane, but it was my understanding it can stand alone with out JFrame.
add these lines to your code.
a) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
b) frame.setVisible(true);
a. will tell your program to finish running with a standard click on the red x in the JFrame (note this is different from your JOptionPane
b. will make the JFrame visible so you can even see and click the red x.
it may be just as easy to do this to JOptionPane, but again I haven't played with it in years.
EDIT: it seems JOptionPane does this automatically, The only reason your program didn't close is because of the invisible JFrame. If you dont have a use for the JFrame try this:
Code :
import javax.swing.*;
public class MainScreen {
public static void main(String[] args) {
System.out.println("begin");
JOptionPane.showMessageDialog(null,"This is a message");
System.out.println("end");
}
}
I removed creating a JFrame all together, and used null to fill the parameter in the method call.
Hope this is what you needed,
Jonathan
Re: JOptionPane preventing program from ending
Thanks JonLane!
That makes a lot of sense now, I thought I was creating a frame for the JOptionPane to live in but now I see they're seperate and have to be closed seperately.
For anyone finding this i've now figured out you can create a JOptionPane that lives alone using:
JOptionPane.showMessageDialog(null, "This is a message");
This does allow the program to end because there is no secret frame hanging about