How can a Swing WindowListener veto JFrame closing

后端 未结 4 1064
北恋
北恋 2020-11-30 14:03

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          


        
4条回答
  •  暖寄归人
    2020-11-30 14:39

    Thanks to the input from Thirler and camickr. This is my solution, which I'm sure that some will hate, but avoids duplicating logic in JFrame, and allows client code to setDefaultCloseOperation as usual.

    class MyFrame {        
        @Override protected void processWindowEvent(WindowEvent e) {
            try {
                super.processWindowEvent(e);
            } catch (SaveOnCloseWindowListener.VetoException x) {}
        }
    }
    
    public class SaveOnCloseWindowListener extends WindowAdapter {
    
        public static class VetoException extends RuntimeException {
        }
    
        private final DocumentController documentController;
    
        public SaveOnCloseWindowListener(DocumentController documentController) {
            this.documentController = documentController;
        }
    
        public void windowClosing(WindowEvent e) {
            if (!documentController.onClose())
                throw new VetoException();
        }
    }
    

提交回复
热议问题