简体   繁体   English

Java Swing使用setDefaultCloseOperation Vs关闭窗口。 addWindowListener

[英]Java Swing closing a window with setDefaultCloseOperation Vs. addWindowListener

In a java swing application what is the difference between the following operations? 在Java swing应用程序中,以下操作之间有什么区别? 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: 实际上它们都是相同的,来自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). 但是,最好调用setDefaultCloseOperation,因为它利用了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. 就像@Berger所说的,如果选择第二种方法,则可以添加其他功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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