This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: How do I programmatically turn off JFrame

What is the correct way to turn off JFrame, as if the user pressed the X close button or Alt + F4 key (on Windows)?

I set the default shutdown action I want by:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Copy the code

It does exactly what I want the above control to do. The question is not about that.

What I really want to do is make the GUI behave the same as pressing the X close button.

Suppose I want to extend WindowAdaptor, and then add an instance of the adapter as a listener by addWindowListener (). I want to see the same call sequence as the X close button with windowDeactivated (), windowClosing (), and windowClosed (). Arguably, it’s not so much closing the window as telling the window to close itself.

Answer 1:

If you want the GUI to behave like clicking the X close button, you need to dispatch a window close event to the window. ExitAction has the ability to close an application, which you can add to a menu item or to any component that is easy to use Actions.

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
Copy the code

Answer 2:

If you are doing this to ensure that the user cannot close the window:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Copy the code

You should then change the pullThePlug() method to

public void pullThePlug(a) {
    . / / this will ensure that WindowListener windowClosing () is invoked
    WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
    // This will hide and place the frame so that the application exits without anything else

    setVisible(false);
    dispose();
    // If there are other similar frames around, they should also be placed.


    System.exit(0); 
}
Copy the code

I found this to be the only good way to combine WindowListener with jframe.do_nothing_on_close.