How can a Swing WindowListener veto JFrame closing

后端 未结 4 1077
北恋
北恋 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:27

    I think that this is the logical expression of Thirler's answer, and kind of what I was trying to avoid.

    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.addWindowListener(new SaveOnCloseWindowListener(fileState, JFrame.EXIT_ON_CLOSE));
    
    public class SaveOnCloseWindowListener extends WindowAdapter {
    
        private final int closeOperation;
        private final Document document;
    
        public SaveOnCloseWindowListener(int closeOperation, Document document) {
            this.closeOperation = closeOperation;
            this.document = document;
        }
    
        public void windowClosing(WindowEvent e) {
            if (!document.onClose())
                doClose((Window) e.getSource());
        }
    
        private void doClose(Window w) {
            switch (closeOperation) {
            case JFrame.HIDE_ON_CLOSE:
                w.setVisible(false);
                break;
            case JFrame.DISPOSE_ON_CLOSE:
                w.dispose();
                break;
            case JFrame.DO_NOTHING_ON_CLOSE:
            default:
                break;
            case JFrame.EXIT_ON_CLOSE:
                System.exit(0);
                break;
            }
        }
    }
    

提交回复
热议问题