Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Swing WindowListener veto JFrame closing

Tags:

java

swing

awt

I have a frame, and want to prompt when the user closes it to save the document. But if they cancel, the frame shouldn't close.

frame.addWindowListener(new SaveOnCloseWindowListener(fileState));
...
public class SaveOnCloseWindowListener extends WindowAdapter {
    private final FileState fileState;

    public SaveOnCloseWindowListener(FileState fileState) {
        this.fileState = fileState;
    }

    public void windowClosing(WindowEvent e) {
        if (!fileState.onQuit())
            cancelClose();  
    }
}

FileState looks at whether the document is dirty. If it isn't it does nothing and returns true. If it is dirty, it asks the user if he wants to save (YES/NO/CANCEL). If the user cancels at this point, it should abort the windowClosing.

All the suggestions I've seen on the net involve explicitly exiting in the windowClosing method, thus overriding the use of JFrame.setDefaultCloseOperation(), and duplicating the code in JFrame.processWindowEvent().

I actually have a dirty solution, but would like to see if there are any cleaner ones.

Cheers

like image 263
Duncan McGregor Avatar asked Sep 23 '10 09:09

Duncan McGregor


People also ask

How do I stop a JFrame from closing?

jFrame. setDefaultCloseOperation(JFrame. DO_NOTHING_ON_CLOSE); That prevents the default behavior which the frame will be closed if the user clicks on the close button.

What is the use of listener window?

Window listeners are commonly used to implement custom window-closing behavior. For example, a window listener is used to save data before closing the window, or to exit the program when the last window closes.


2 Answers

The right way is set JFrame.setDefaultCloseOperation to DO_NOTHING_ON_CLOSE when the window is created. And then just calling setVisible(false) or dispose() when your user accepts the close, or doing nothing when the close isn't accepted.

The whole purpose of JFrame.setDefaultCloseOperation is only to prevent the need to implement WindowListeners for the most simple actions. The actions performed by these default close operations are very simple.

EDIT:

I've added the solution I'm describing. This assumes you want the frame to be fully deleted.

frame.setDefaultCloseOperation(setDefaultCloseOperation);
frame.addWindowListener(new SaveOnCloseWindowListener(fileState));
...

public class SaveOnCloseWindowListener extends WindowAdapter {
    private final FileState fileState;

    public SaveOnCloseWindowListener(FileState fileState) {
        this.fileState = fileState;
    }

    public void windowClosing(WindowEvent e) {
        if (fileState.onQuit())
            frame.dispose();
    }
}
like image 152
Thirler Avatar answered Oct 03 '22 22:10

Thirler


Closing an Application might make the process a little easier for you.

like image 29
camickr Avatar answered Oct 03 '22 22:10

camickr