簡體   English   中英

Java Swing使用setDefaultCloseOperation Vs關閉窗口。 addWindowListener

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

在Java swing應用程序中,以下操作之間有什么區別? 我何時更願意使用一個?

我在網上散布的不同示例中都看到了這兩種情況:

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

- 要么 -

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

第二種方法似乎需要很多代碼,所以我想知道為什么我看到它被如此廣泛地使用。 與第一種方法相比,這種方法有什么優勢嗎?

實際上它們都是相同的,來自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;
            }
        }
    }

但是,最好調用setDefaultCloseOperation,因為它利用了JFrame(re-usablity)的當前現有代碼。

如果您只想標准關閉,我將使用第一個選項。 就像@Berger所說的,如果選擇第二種方法,則可以添加其他功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM