Java dialog does not dispose

后端 未结 1 1860
鱼传尺愫
鱼传尺愫 2021-01-23 05:59

Java noob here. My Swing class that extends JDialog does not dispose when the user presses the Windows Close button - java.exe stays in memory. I\'ve stripped the

相关标签:
1条回答
  • 2021-01-23 06:15

    You're creating a JFrame and never disposing it here:

    public WhyNoDispose(String title) {
        super(new JFrame(title), ModalityType.APPLICATION_MODAL); // *********
        pack();
    }
    

    So since the JFrame is alive and a GUI has been rendered, the Swing event thread keeps on running.

    If you instead make the JFrame behave so that the program exits on JFrame close, and then explicitly dispose of the JFrame, your program now exits:

    import java.awt.Window;
    
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    
    public class WhyNoDispose extends JDialog {
       public static void main(String[] args) {
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                try {
                   WhyNoDispose frame = new WhyNoDispose("my title");
                   frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                   JFrame win = (JFrame) frame.getOwner();
                   win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.setVisible(true);
                   win.dispose();
                   // System.exit(0);
                } catch (Exception e) {
                   e.printStackTrace();
                }
             }
          });
       }
    
       public WhyNoDispose(String title) {
          super(new JFrame(title), ModalityType.APPLICATION_MODAL);
          pack();
       }
    }
    

    But this is very kludgy code, to say the least -- what if the owning window isn't a JFrame? What if it's null?

    Another solution is to use no JFrame at all, so that when the JDialog is disposed, there's no persisting window left over to make the event thread persist:

    import java.awt.Window;
    
    import javax.swing.JFrame;
    import javax.swing.JDialog;
    
    public class WhyNoDispose extends JDialog {
       public static void main(String[] args) {
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                try {
                   WhyNoDispose frame = new WhyNoDispose("my title");
                   frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                   frame.setVisible(true);
                } catch (Exception e) {
                   e.printStackTrace();
                }
             }
          });
       }
    
       public WhyNoDispose(String title) {
          super((JFrame)null, title);
          pack();
       }
    }
    
    0 讨论(0)
提交回复
热议问题