I detect when a window is closed by the user so I can prompt to save, by adding a window listener and windowClosing(). If there is unsaved work I request focus for that window, then use JOptionPane.
This works if that window is focused. But if the user closes the window by hovering over the taskbar and clicking the close button there, then sometimes the window gains focus but sometimes just flashes on the task bar (and does not get focused). I need this to behave consistently. If this is platform-specific there might not be a solution (I am using Windows 11).
window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
window.addWindowListener(new WindowAdapter() {
public void windowClosing(final WindowEvent e) {
window.requestFocus();
window.toFront();
JOptionPane.showMessageDialog(window, "Not saved", "Not saved", JOptionPane.ERROR_MESSAGE);
}
});
Using SwingUtilities.invokeLater separately on the focus request and the JOptionPane makes no difference.

window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);towindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);. MethodwindowClosingwill still be invoked.windowis iconified and I try to close it from taskbar like the way you described, then theJOptionPaneappears, but the window is not deiconified. But I am using Windows 10 so this may be the reason for the different behavior. Eitherway, assumingwindowis aFrame, then putting awindow.setExtendedState(Frame.NORMAL);call beforewindow.toFront();fixed the issue (the window now pops up every time).window.requestFocus();was not needed. I am not posting this as an answer though since I can't test on Windows 11 now.