How to close a GUI when I push a JButton?

185,638

Solution 1

Add your button:

JButton close = new JButton("Close");

Add an ActionListener:

close.addActionListner(new CloseListener());

Add a class for the Listener implementing the ActionListener interface and override its main function:

private class CloseListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        //DO SOMETHING
        System.exit(0);
    }
}

This might be not the best way, but its a point to start. The class for example can be made public and not as a private class inside another one.

Solution 2

By using System.exit(0); you would close the entire process. Is that what you wanted or did you intend to close only the GUI window and allow the process to continue running?

The quickest, easiest and most robust way to simply close a JFrame or JPanel with the click of a JButton is to add an actionListener to the JButton which will execute the line of code below when the JButton is clicked:

this.dispose();

If you are using the NetBeans GUI designer, the easiest way to add this actionListener is to enter the GUI editor window and double click the JButton component. Doing this will automatically create an actionListener and actionEvent, which can be modified manually by you.

Solution 3

See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)1. You might also use EXIT_ON_CLOSE, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.

The 'button' to invoke this operation is already on a frame.

  1. See this answer to How to best position Swing GUIs? for a demo. of the DISPOSE_ON_CLOSE functionality.

    The JRE will end after all 3 frames are closed by clicking the X button.

Solution 4

You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.

The System.exit(0) will terminates the currently running Java Virtual Machine.

Solution 5

In Java 8, you can use Lambda expressions to make it simpler.

Close application

JButton btnClose = new JButton("Close");
btnClose.addActionListener(e -> System.exit(0));

Close window

JButton btnClose = new JButton("Close");
btnClose.addActionListener(e -> this.dispose());
Share:
185,638
PulsePanda
Author by

PulsePanda

Im kinda a noob when it comes to programming, but i'm better than a lot of people i know. i love java with a passion, but i dont know much about it.

Updated on July 09, 2022

Comments

  • PulsePanda
    PulsePanda almost 2 years

    Does anyone know how to make a jbutton close a gui? I think it is like System.CLOSE(0); but that didnt work. it also could be exitActionPerformed(evt);, but that didn't work either. just the line of code will work.

    EDIT: never mind guys. the answer was System.exit(0);. thanks for the help though!