1

I am new in Java Form Application development using Swing. What is the suitable code for exit button that will exit the application?

For example: In C# (.NET Framework) we use Application.Exit(); as the code for exit what button. What is the equivalent code in Java to exit an application?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sondhi
  • 51
  • 1
  • 4
  • 9
  • 1
    Given it is Swing, I'd say `JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)`.. – Andrew Thompson Aug 22 '14 at 12:07
  • 3
    @AndrewThompson I think you mean EXIT_ON_CLOSE. And then you'd let the button close the JFrame. Relevant possible duplicate: http://stackoverflow.com/questions/1234912/how-to-programmatically-close-a-jframe – Gimby Aug 22 '14 at 12:09
  • 4
    @Gimby No I most definitely ***did not*** meand `EXIT_ON_CLOSE`. One should not 'kill the VM' if other threads are running. If they aren't running, `DISPOSE_ON_CLOSE` is sufficient. Otherwise, those threads should be shut down/cleaned up explicitly. – Andrew Thompson Aug 22 '14 at 12:11
  • 1
    possible duplicate of [How to close a Java Swing application from the code](http://stackoverflow.com/questions/258099/how-to-close-a-java-swing-application-from-the-code) – Alexandru Cimpanu Aug 22 '14 at 12:17
  • @AndrewThompson never thought about it that way. Thanks! – Gimby Aug 22 '14 at 12:22

5 Answers5

9
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

Now for a bit of explanation. The closest equivalent to as seen in the question is..

jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

But that kills the entire JRE irrespective of other non-daemon threads that are running. If they are running, they should be shut down or cleaned up explicitly.

If there are no other non-daemon threads running, DISPOSE_ON_CLOSE will dispose the current JFrame and end the virtual machine.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • disagree see there difference for many JFrame/JDialogs in one JVM instance(last turn of the light), JVM can stays still alive after JFrame.DISPOSE_ON_CLOSE is called, isn't it – mKorbel Aug 22 '14 at 12:31
  • 1
    @mKorbel *"JVM can stays still alive after JFrame.DISPOSE_ON_CLOSE is called"* Sure thing. Of course, if it stays alive after the last GUI element is closed, it is time to start looking at what is keeping the JVM from ending. – Andrew Thompson Aug 22 '14 at 12:37
  • I also disagree. `JFrame.EXIT_ON_CLOSE` is just fine, if you handle cleanup in an overridden `JFrame.processWindowEvent(WindowEvent)` checking for `WindowEvent.WINDOW_CLOSING` events. – predi Aug 22 '14 at 12:38
  • @Andrew Thompson `it is time to start looking at what is keeping` - right I'm miss there that JVM must be shutdown by using System.exit in the case that there is/are active thread(s) – mKorbel Aug 22 '14 at 12:41
  • +1 specially for last 2 paragraphs. However I'd prefer `JFrame.DO_NOTHING_ON_CLOSE` and process all pending stuff (such as log-out, logger stuff, resource liberation, ...) adding a `WindowAdapter` to the frame and overriding `windowClosing()` method, and finally do the `frame.dispose()` call – dic19 Aug 22 '14 at 12:46
3

If you want to create a button which exits the application when the user clicks it, try this:

JButton exit = new JButton("exit");

ActionListener al = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }
};

exit.addActionListener(al);

Now when you press on that button the application will exit.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
Eyadkht
  • 81
  • 7
2

@AndrewThompson is right about JFrame.EXIT_ON_CLOSE but you can take steps to avoid just killing stuff.

JFrame.EXIT_ON_CLOSE is just fine, if you handle cleanup in an overridden JFrame.processWindowEvent(WindowEvent) checking for WindowEvent.WINDOW_CLOSING events.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.Timer;

public class ExitJFrame extends JFrame {

    public ExitJFrame() {
        setLayout(new BorderLayout());

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton button = new JButton("Exit");
        add(button);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ExitJFrame.this.processWindowEvent(
                        new WindowEvent(
                                ExitJFrame.this, WindowEvent.WINDOW_CLOSING));
            }
        });

        setSize(200, 200);
        setLocationRelativeTo(null);
    }

    @Override
    protected void processWindowEvent(WindowEvent e) {
        // more powerful as a WindowListener, since you can consume the event 
        // if you so please - asking the user if she really wants to exit for
        // example, do not delegate to super if consuming.
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            doCleanup();
            super.processWindowEvent(e); 
        } else {        
            super.processWindowEvent(e); 
        }
    }

    private void doCleanup() {
        final JDialog dialog = new JDialog(this, true);
        dialog.setLayout(new BorderLayout());
        dialog.setUndecorated(true);
        JProgressBar progress = new JProgressBar();
        dialog.add(progress);
        dialog.add(new JLabel("Waiting for non-daemon threads to exit gracefully..."), BorderLayout.NORTH);
        progress.setIndeterminate(true);

        Timer timer = new Timer(2000, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        });
        timer.setRepeats(false);
        timer.start();
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }

    public static void main (String[] args) {
        new ExitJFrame().setVisible(true);
    }

}
predi
  • 5,528
  • 32
  • 60
0

If you're talking about a JButton that you want to put into your form, then you want to invoke JFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) in your constructor for the form, and then your button handler can invoke

dispose()

to close the form.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
0

Very simple answer is as @Andrew Thompson said.

jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

OR

jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

and if u want to make it in other way by code. then u can put this code anywhere. in events.

System.exit(0);

hope this will help.

Kishan Bheemajiyani
  • 3,429
  • 5
  • 34
  • 68