简体   繁体   中英

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?

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM