Java Listen to application closing

211 views Asked by At

I am trying to catch the Event related to the application closure. Unfortunately the WindowListener does not do it. I have put the Listener on the main JFrame.

jFrame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        try {
            FileUtils.cleanDirectory(new File("./temp/"));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        System.exit(0);
    }
});

Why is the windowClosing never called in any case?


@khelwood this is the code for the JFrame and its construction in the Application.

public class EmeryJFrame extends JFrame {

public EmeryJFrame() throws HeadlessException {
    super();
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                Debug.infomess("clean exit");
                try {
                    FileUtils.cleanDirectory(new File("./temp/"));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                e.getWindow().dispose();
                System.exit(0);
                }
        });
}}

The main Application:

public static void main(String[] args)  {
      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
      new SVGApplication();
}

public class SVGApplication   {
      protected SVGApplication() {
          jFrame = new EmeryJFrame();
      }
}

The issue does not come from the LookAndFeel (tested). I also removed the 'try catch' for better readability.

1

There are 1 answers

1
Senior Pomidor On
jFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

jFrame.addWindowListener(new WindowAdapter()
        {
           public void windowClosing(WindowEvent e) {
                try {
                    FileUtils.cleanDirectory(new File("./temp/"));
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                e.getWindow().dispose();
                System.exit(0);
           }
        });