javaswingjframenetbeans-7windowlistener

How to stop closing JFrame form?


I want to Stop accidentally closings in my project. I'm using JFrame Form as Home page. When I click Home window's close button I put Exit cord in Yes Option. I want to stop closing when I click No Option. Is there any way. Here is my cord. I'm using netbeans 7.3

 private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
 int i= JOptionPane.showConfirmDialog(null, "Are you sure to exit?");
    if (i == JOptionPane.YES_OPTION) {
        System.exit(0);
    } else{
        new Home().setVisible(true);

    }
}

Solution

  • How about

    class MyGUI extends JFrame {
    
        public MyGUI() {
            setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);// <- don't close window 
                                                                 // when [X] is pressed
    
            final MyGUI gui = this;
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    int i = JOptionPane.showConfirmDialog(gui,
                            "Are you sure to exit?", "Closing dialog",
                            JOptionPane.YES_NO_OPTION);
                    if (i == JOptionPane.YES_OPTION) {
                        System.exit(0);
                    }
                }
            });
    
            setSize(200, 200);
            setVisible(true);
        }
    
        //demo
        public static void main(String[] args) {
            new MyGUI();
        }
    }