How to programmatically close a JFrame

前端 未结 17 912
深忆病人
深忆病人 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条回答
  • 2020-11-22 06:39

    If by Alt-F4 or X you mean "Exit the Application Immediately Without Regard for What Other Windows or Threads are Running", then System.exit(...) will do exactly what you want in a very abrupt, brute-force, and possibly problematic fashion.

    If by Alt-F4 or X you mean hide the window, then frame.setVisible(false) is how you "close" the window. The window will continue to consume resources/memory but can be made visible again very quickly.

    If by Alt-F4 or X you mean hide the window and dispose of any resources it is consuming, then frame.dispose() is how you "close" the window. If the frame was the last visible window and there are no other non-daemon threads running, the program will exit. If you show the window again, it will have to reinitialize all of the native resources again (graphics buffer, window handles, etc).

    dispose() might be closest to the behavior that you really want. If your app has multiple windows open, do you want Alt-F4 or X to quit the app or just close the active window?

    The Java Swing Tutorial on Window Listeners may help clarify things for you.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 06:39

    Exiting from Java running process is very easy, basically you need to do just two simple things:

    1. Call java method System.exit(...) at at application's quit point. For example, if your application is frame based, you can add listener WindowAdapter and and call System.exit(...) inside its method windowClosing(WindowEvent e).

    Note: you must call System.exit(...) otherwise your program is error involved.

    1. Avoiding unexpected java exceptions to make sure the exit method can be called always. If you add System.exit(...) at right point, but It does not mean that the method can be called always, because unexpected java exceptions may prevent the method from been called.

    This is strongly related to your programming skills.

    ** Following is a simplest sample (JFrame based) which shows you how to call exit method

    import java.awt.event.*;
    import javax.swing.*;
    
    public class ExitApp extends JFrame
    {
       public ExitApp()
       {
          addWindowListener(new WindowAdapter()
          {
             public void windowClosing(WindowEvent e)
             {
               dispose();
               System.exit(0); //calling the method is a must
             }
          });
       }
    
       public static void main(String[] args)
       {
          ExitApp app=new ExitApp();
          app.setBounds(133,100,532,400);
          app.setVisible(true);
       }
    }
    
    0 讨论(0)
  • 2020-11-22 06:39

    Best way to close a Swing frame programmatically is to make it behave like it would when the "X" button is pressed. To do that you will need to implement WindowAdapter that suits your needs and set frame's default close operation to do nothing (DO_NOTHING_ON_CLOSE).

    Initialize your frame like this:

    private WindowAdapter windowAdapter = null;
    
    private void initFrame() {
    
        this.windowAdapter = new WindowAdapter() {
            // WINDOW_CLOSING event handler
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                // You can still stop closing if you want to
                int res = JOptionPane.showConfirmDialog(ClosableFrame.this, "Are you sure you want to close?", "Close?", JOptionPane.YES_NO_OPTION);
                if ( res == 0 ) {
                    // dispose method issues the WINDOW_CLOSED event
                    ClosableFrame.this.dispose();
                }
            }
    
            // WINDOW_CLOSED event handler
            @Override
            public void windowClosed(WindowEvent e) {
                super.windowClosed(e);
                // Close application if you want to with System.exit(0)
                // but don't forget to dispose of all resources 
                // like child frames, threads, ...
                // System.exit(0);
            }
        };
    
        // when you press "X" the WINDOW_CLOSING event is called but that is it
        // nothing else happens
        this.setDefaultCloseOperation(ClosableFrame.DO_NOTHING_ON_CLOSE);
        // don't forget this
        this.addWindowListener(this.windowAdapter);
    }
    

    You can close the frame programmatically by sending it the WINDOW_CLOSING event, like this:

    WindowEvent closingEvent = new WindowEvent(targetFrame, WindowEvent.WINDOW_CLOSING);
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closingEvent);
    

    This will close the frame like the "X" button was pressed.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题