How to programmatically close a JFrame

前端 未结 17 978
深忆病人
深忆病人 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

    Posting what was in the question body as CW answer.

    Wanted to share the results, mainly derived from following camickr's link. Basically I need to throw a WindowEvent.WINDOW_CLOSING at the application's event queue. Here's a synopsis of what the solution looks like

    // closing down the window makes sense as a method, so here are
    // the salient parts of what happens with the JFrame extending class ..
    
        public class FooWindow extends JFrame {
            public FooWindow() {
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setBounds(5, 5, 400, 300);  // yeah yeah, this is an example ;P
                setVisible(true);
            }
            public void pullThePlug() {
                    WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
                    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
            }
        }
    
    // Here's how that would be employed from elsewhere -
    
        // someplace the window gets created ..
        FooWindow fooey = new FooWindow();
        ...
        // and someplace else, you can close it thusly
        fooey.pullThePlug();
    

提交回复
热议问题