开发者

How do I close a java application from the code

开发者 https://www.devze.com 2023-03-25 22:40 出处:网络
How do you close a java application f开发者_如何学编程rom the code?You call System.exit: System.exit(0);

How do you close a java application f开发者_如何学编程rom the code?


You call System.exit:

System.exit(0);


I believe that by most standards, System.exit() is a not very OOP way of closing applications, I've always been told that the proper way is to return from main. This is somewhat a bit of a pain and requires a good design but I do believe its the "proper" way to exit


If you're terminating a Swing app, I would do an EXIT_ON_CLOSE

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

before System.exit(0). This is better since you can write a Window Listener to make some cleaning operations before actually leaving the app.

That window listener allows you to exit the app from the code:

public void windowClosing(WindowEvent e) {
    displayMessage("WindowListener method called: windowClosing.");
    //A pause so user can see the message before
    //the window actually closes.
    ActionListener task = new ActionListener() {
        boolean alreadyDisposed = false;
        public void actionPerformed(ActionEvent e) {
            if (frame.isDisplayable()) {
                alreadyDisposed = true;
                frame.dispose();
            }
        }
    };
    Timer timer = new Timer(500, task); //fire every half second
    timer.setInitialDelay(2000);        //first delay 2 seconds
    timer.setRepeats(false);
    timer.start();
}

public void windowClosed(WindowEvent e) {
    //This will only be seen on standard output.
    displayMessage("WindowListener method called: windowClosed.");
}


If you're running an application, System.exit will work.

System.exit(int);

In an applet, however, you'll have to do something along the lines of applet.getAppletContext().showDocument("landingpage.html"); because of browser permissions. It won't just let you close the browser window.


You use System.exit(int), where a value of 0 means the application closed successfully and any other value typically means something was wrong. Usually you just see a return value of 1 along with a message printed to sysout or syserr if the application did not close successfully.

Everything is fine, application shut down correctly:
System.exit(0)

Something went wrong, application did not shut down correctly:
System.err.println("some meaningful message"); System.exit(1)

0

精彩评论

暂无评论...
验证码 换一张
取 消