hay que añadir un WindowListener
a la JFrame
.
Dentro del método windowClosing
, puede proporcionar el código requerido.
Por ejemplo:.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClosingFrame extends JFrame {
private JMenuBar MenuBar = new JMenuBar();
private JFrame frame = new JFrame();
private static final long serialVersionUID = 1L;
private JMenu File = new JMenu("File");
private JMenuItem Exit = new JMenuItem("Exit");
public ClosingFrame() {
File.add(Exit);
MenuBar.add(File);
Exit.addActionListener(new ExitListener());
WindowListener exitListener = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.OK_OPTION) {
System.exit(0);
}
}
};
frame.addWindowListener(exitListener);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setJMenuBar(MenuBar);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
private class ExitListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.OK_OPTION) {
System.exit(0);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ClosingFrame cf = new ClosingFrame();
}
});
}
}
1) ITYM 'frame.addWindowListener (nuevo WindowAdapter() {' (de lo contrario se trata de un error de compilación) 2) El JRE no terminará desde el EDT aún se está ejecutando. Esta es una de las raras ocasiones en que podría ser necesario llamar a 'System.exit (0)'. –
@AndrewThompson, ¿qué sugieres que sea la forma más segura de cerrar una aplicación en lugar de System.exit (0); ? – Andrei0427
Bueno, es posible que primero mire los hilos en ejecución y compruebe que solo se está ejecutando el EDT. De ser así, sería bastante seguro finalizar la JVM usando 'System.exit (0)'. Pero hay una mejor solución aquí, vea mi respuesta. –