0

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?

tjwrona1992
  • 8,614
  • 8
  • 35
  • 98
  • 3
    The second way lets you do additional things : clean resources, save stuff, contact the police, whatever. See : http://stackoverflow.com/questions/6084039/create-custom-operation-for-setdefaultcloseoperation/6084220 – Arnaud Jun 09 '16 at 16:06

2 Answers2

2

Actually they both the same , this code from JFrame:

   protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);

        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            switch(defaultCloseOperation) {
              case HIDE_ON_CLOSE:
                 setVisible(false);
                 break;
              case DISPOSE_ON_CLOSE:
                 dispose();
                 break;
              case DO_NOTHING_ON_CLOSE:
                 default:
                 break;
              case EXIT_ON_CLOSE:
                  // This needs to match the checkExit call in
                  // setDefaultCloseOperation
                System.exit(0);
                break;
            }
        }
    }

However, calling setDefaultCloseOperation is preferable since it utilize the current existing code of JFrame(re-usablity).

Jalal Kiswani
  • 738
  • 5
  • 11
1

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.

Weasemunk
  • 455
  • 4
  • 16