简体   繁体   中英

calling dispose() does not close JFrame

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);
    }
}

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM