2

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.

An example of what is currently happening if the window is not already focused when it is closed by the user

4
  • I suggest that you change window.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); to window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);. Method windowClosing will still be invoked. Commented Oct 15 at 7:46
  • 1
    I can't reproduce the exact same behavior. For me, when the window is iconified and I try to close it from taskbar like the way you described, then the JOptionPane appears, but the window is not deiconified. But I am using Windows 10 so this may be the reason for the different behavior. Eitherway, assuming window is a Frame, then putting a window.setExtendedState(Frame.NORMAL); call before window.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. Commented Oct 15 at 7:47
  • @Abra If I use WindowConstants.EXIT_ON_CLOSE then other windows within the program will end up being closed without warning. Commented Oct 15 at 7:59
  • @gthantop Thank you for the suggestion - setExtendedState works nicely when all windows are iconified, but doesn't always work when I'm in another window, e.g. like now when I'm in Chrome. So problem is partially solved but not completely! Commented Oct 15 at 8:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.