Search code examples
javaswinguser-interfacejframewindow

Java Swing closing a window with setDefaultCloseOperation Vs. addWindowListener


In a java swing application what is the difference between the following operations? When would I prefer to use one over the other?

I have seen both of these in different examples strewn across the internet:

// Have the window exit on close
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

- OR -

// Set up a window listener to exit on close
mainFrame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent windowEvent) {
        System.exit(0);
    }
});

The second approach seems to be a lot more code so I'm wondering why I see it so widely used. Is there any advantage to this approach over the first one?


Solution

  • I would use the first option if you only want a standard close. Like @Berger said, you can add additional functionality if you choose the second method.