How to programmatically close a JFrame

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

    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);
       }
    }
    

提交回复
热议问题