为setDefaultCloseOperation创建自定义操作?

问题描述:

我想让我的Java应用程序在按下关闭十字按钮时调用我自己的自定义函数。据我所知,可能没办法,因为 setDefaultCloseOperation 根本没有重载。

I want to make my Java Application to call my own custom made function when the "close" cross button is pressed. as far as i see there may be no way since setDefaultCloseOperation has no overloads at all.

知道如何实现这一目标吗?

Any idea how this can be achieved?

也许这个,但在那之前阅读教程 WindowListener ,有一些/另一种选择

maybe this one, but before that read tutorial WindowListener posted by Howard, there are some/another options

WindowListener exitListener = new WindowAdapter() {

    @Override
    public void windowClosing(WindowEvent e) {
        int confirm = JOptionPane.showOptionDialog(
             null, "Are You Sure to Close Application?", 
             "Exit Confirmation", JOptionPane.YES_NO_OPTION, 
             JOptionPane.QUESTION_MESSAGE, null, null, null);
        if (confirm == 0) {
           System.exit(0);
        }
    }
};
frame.addWindowListener(exitListener);