1

I have created three classes:

public class Gui extends JFrame {

private final JButton buttonClose = new JButton("Close");

private final MyButtonListener buttonListener = new MyButtonListener(this);
private final MyWindowListener windowListener = new MyWindowListener();

public SwitchGuiExtListeners() {
    super("Switch");
    setSize(200, 150);
    setLayout(new BorderLayout());
    add(buttonClose, BorderLayout.EAST);
    buttonClose.addActionListener(this.buttonListener);
    this.addWindowListener(this.windowListener);
    setVisible(true);
}

public JButton getButtonClose() {
    return buttonClose;
}
}

public class SwitchGuiWindowListener implements WindowListener{
...
@Override
    public void windowClosing(WindowEvent e) {
        System.exit(0);

    }
...
}

public class MyButtonListener implements ActionListener {
private final Gui gui;
public MyButtonListener (final Gui gui) {
    this.gui = gui;
}

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == gui.getButtonClose()){
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //System.exit(0);
    }
}
}

If I use the gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); my frame doesn't close. But when I use the System.exit(0) it works. Why can't I use the setDefaultCloseOperation(..)?

tamaramaria
  • 173
  • 1
  • 4
  • 17

1 Answers1

2

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); does not close a JFrame. It simply tells that the JFrame must exit when the close button on top-right corner of a window is clicked i.e., just sets the behavior but does trigger an exit.

To close a JFrame, use something like this:

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

Source: https://stackoverflow.com/a/1235994/1866196

Community
  • 1
  • 1
skrtbhtngr
  • 2,223
  • 23
  • 29
  • Thank you, but what exactly is the difference then between frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); and System.exit(0);? – tamaramaria Jun 07 '15 at 16:58
  • In case it's not set to exit on close, the event may be fired, and still not terminate the program. – Mordechai Jun 07 '15 at 17:01
  • 1
    In simple terms `System.exit(0)` terminates the application. `frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));` trigger the WINDOW_CLOSING event which can be handled by an event handler, giving you the opportunity to run any clean-up code like releasing database connections etc. – skrtbhtngr Jun 07 '15 at 17:02