How to close a GUI when I push a JButton?

PulsePanda picture PulsePanda · Dec 26, 2011 · Viewed 172.6k times · Source

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!

Answer

Baarn picture Baarn · Dec 26, 2011

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.