windowClosing() method is not getting called

673 views Asked by At
import javax.swing.*;
import java.awt.event.*;

public class Test  {

    Test() {
        JFrame f=new JFrame("CloseIt");
        f.setVisible(true);
        f.setSize(400,200);
        f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        f.addWindowListener(new WindowAdapter(){
            public void WindowClosing(WindowEvent e)
            {
                System.out.print("In Windowclosing opr");
                f.dispose();
            }
        });
    }

    public static void main(String arg[]) {
        Test t=new Test();
    }
}

I actually wanted to ask the user whether he wants to save the file before closing it. But whenever I close the frame (cross button), nothing happens. windowClosing() is not even getting called.

2

There are 2 answers

0
Thomas Kläger On

You named your method WindowClosing().

The method that get's called is however windowClosing().

The best recommendation is to annotate your methods with @Override so that the compiler knows that you want to override a method and can produce an error message if your method doesn't override a superclass method:

    f.addWindowListener(new WindowAdapter(){
        @Override
        public void windowClosing(WindowEvent e)
        {
            ...
        }
    });
1
Dhanushka sasanka On

Edit your WindowClosing() method as windowClosing()

how about my solution yours one is right too.

  addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                int confirmedPane = JOptionPane.showConfirmDialog(null,
                        "Are you sure you want to exit the program?",
                        "Exit Program Message Box",
                        JOptionPane.YES_NO_OPTION);

                if (confirmedPane == JOptionPane.YES_OPTION) {
                    System.out.println("Yes is the option");
                } else {
                    dispose();
                }
            }
        });