KaitoX
KaitoX

Reputation: 5

Need advice on creating a closing button for a small Java program

I am a novice as already stated and looking to create a button to close the program out. I am not talking about making sure the typical window close (Red X) terminates the program. I wish to make an additional button within my frame that when clicked will terminate the program as well.

Upvotes: 0

Views: 340

Answers (4)

Andrew Thompson
Andrew Thompson

Reputation: 168825

import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class GoodbyeWorld {

    GoodbyeWorld() {
        final JFrame f = new JFrame("Close Me!");
        // If there are no non-daemon threads running,  
        // disposing of this frame will end the JRE. 
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // If there ARE non-daemon threads running,  
        // they should be shut down gracefully.  :) 

        JButton b = new JButton("Close!");
        JPanel p = new JPanel(new GridLayout());
        p.setBorder(new EmptyBorder(10,40,10,40));
        p.add(b);

        f.setContentPane(p);
        f.pack();
        f.setLocationByPlatform(true);
        f.setVisible(true);

        ActionListener closeListener = new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                f.setVisible(false);
                f.dispose();
            }
        };
        b.addActionListener(closeListener);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                new GoodbyeWorld();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

Upvotes: 2

Maciej Trybiło
Maciej Trybiło

Reputation: 1207

If you are extending the org.jdesktop.application.Application class (Netbeans would do that) you could invoke exit() in your app class, so:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        yourApp.exit();
    }
});

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347204

If you have set up the main application frame's (JFrame) defaultCloseOperation to JFrame.EXIT_ON_CLOSE then simply calling the frame's dispose method will terminate the program.

JButton closeButton = JButton("Close");
closeButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        yourReferenceToTheMainFrame.dispose();
    }
});

If not, then you will need to add to the actionPerformed method a call to System.exit(0);

Upvotes: 5

FThompson
FThompson

Reputation: 28687

You can add an ActionListener to your button which, upon action being performed, exits from the JVM.

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

Upvotes: 5

Related Questions