@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);
}
}