Reputation: 366
I am new to Swing, and got stuck in coding a very simple application that should display a JFrame. I tracked it down to the following code below.
The window does not close, the JVM runs forever, the window MUST be closed via clicking the X. If I instead use JFrame fr = new JFrame("Test")
, the dispose methods does its job.
Why does the JFrame not close when dispose() is called here, what is to do to make it happen?
import javax.swing.JFrame;
public class HelloWorld {
public static void main(String[] args) {
JFrame fr = new Canvas("Test");
fr.setSize(100, 100);
fr.setVisible(true);
System.out.println("Test");
fr.dispose();
}
}
class Canvas extends JFrame {
Canvas(String title) {
JFrame fr = new JFrame(title);
fr.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
fr.setVisible(true);
}
}
Upvotes: 1
Views: 1409
Reputation: 285405
You're creating two JFrame objects here, one you set the defaultCloseOperation on (fr), and one you try to call dispose on, so it makes sense that things are not working. Instead create only one object. Get rid of the fr variable. So change this:
class Canvas extends JFrame {
Canvas(String title) {
JFrame fr = new JFrame(title);
fr.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
fr.setVisible(true);
}
}
to this:
class Canvas extends JFrame {
Canvas(String title) {
super(title);
// JFrame fr = new JFrame(title);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
}
Upvotes: 4