Ben
Ben

Reputation: 59

How do I close a java application from the code

How do you close a java application from the code?

Upvotes: 5

Views: 40066

Answers (5)

pasha
pasha

Reputation: 130

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

Upvotes: 5

fireshadow52
fireshadow52

Reputation: 6516

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

Upvotes: 3

Nate W.
Nate W.

Reputation: 9249

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)

Upvotes: 1

Peter Kazazes
Peter Kazazes

Reputation: 3628

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.

Upvotes: 2

João Silva
João Silva

Reputation: 91299

You call System.exit:

System.exit(0);

Upvotes: 15

Related Questions