How to programmatically close a JFrame

前端 未结 17 982
深忆病人
深忆病人 2020-11-22 05:42

What\'s the correct way to get a JFrame to close, the same as if the user had hit the X close button, or pressed Alt+F4 (on W

17条回答
  •  旧时难觅i
    2020-11-22 06:39

    If you have done this to make sure the user can't close the window:

    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    

    Then you should change your pullThePlug() method to be

    public void pullThePlug() {
        // this will make sure WindowListener.windowClosing() et al. will be called.
        WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
    
        // this will hide and dispose the frame, so that the application quits by
        // itself if there is nothing else around. 
        setVisible(false);
        dispose();
        // if you have other similar frames around, you should dispose them, too.
    
        // finally, call this to really exit. 
        // i/o libraries such as WiiRemoteJ need this. 
        // also, this is what swing does for JFrame.EXIT_ON_CLOSE
        System.exit(0); 
    }
    

    I found this to be the only way that plays nice with the WindowListener and JFrame.DO_NOTHING_ON_CLOSE.

提交回复
热议问题