Bạn cần phải thêm một WindowListener
đến JFrame
.
Bên trong phương thức windowClosing
, bạn có thể cung cấp mã được yêu cầu.
Ví dụ:.
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 (WindowAdapter mới() { '(nếu không nó là một lỗi biên dịch) 2) JRE sẽ không kết thúc kể từ EDT vẫn đang chạy. Đây là một trong những trường hợp hiếm hoi khi gọi 'System.exit (0)' có thể là cần thiết. –
@AndrewThompson những gì bạn sẽ đề nghị là cách an toàn nhất để đóng một ứng dụng thay vì System.exit (0); ? – Andrei0427
Vâng, bạn có thể lần đầu tiên nhìn vào các chủ đề đang chạy và kiểm tra xem nó chỉ là EDT vẫn đang chạy. Nếu vậy, sẽ khá an toàn khi kết thúc JVM bằng cách sử dụng 'System.exit (0)'. Nhưng có một giải pháp tốt hơn ở đây, xem câu trả lời của tôi .. –