Java - how do I prevent WindowClosing from actually closing the window

后端 未结 7 1697
灰色年华
灰色年华 2020-12-03 04:23

I seem to have the reverse problem to most people. I have the following pretty standard code to see if the user wants to do some saves before closing the window:

         


        
7条回答
  •  难免孤独
    2020-12-03 04:57

    I've just tried this minimal test case:

    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    
    import javax.swing.JFrame;
    import javax.swing.WindowConstants;
    
    public class test {
    
        public static void main(String[] args) {
            final JFrame frame = new JFrame("Test");
            frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent ev) {
                    //frame.dispose();
                }
            });
            frame.setVisible(true);
    
        }
    
    }
    

    If I keep the dispose call commented, and hit the close button, the window doesn't exit. Uncomment that and hit the close button, window closes.

    I'd have to guess that something is wrong in your logic to set your "close" variable. Try double checking that.

提交回复
热议问题