繼承 `JFrame` 的視窗,點擊自訂「退出」按鈕或視窗關閉鈕無法結束應用程式。`setDefaultCloseOperation`、`addWindowListener` 均無效。
// 1. 視窗關閉操作設為 EXIT_ON_CLOSE(關閉視窗即退出 JVM)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 2. 自訂退出按鈕
btnExit.addActionListener(e -> {
// 執行清理:關閉資料庫、儲存設定、停止執行緒池
cleanupResources();
System.exit(0); // 強制終止 JVM
});
// 3. 視窗監聽器(可選,用於確認對話框)
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int opt = JOptionPane.showConfirmDialog(
MyFrame.this, "確定要離開?", "確認", JOptionPane.YES_NO_OPTION);
if (opt == JOptionPane.YES_OPTION) {
cleanupResources();
System.exit(0);
}
// 否則不處理,視窗保持開啟(需設定 DO_NOTHING_ON_CLOSE)
}
});