程序关闭时添加对话框

Add dialog box when the program is clossed

我想在有人关闭框架时添加一个选项,以检查是否有任何线程 运行 如果有,我想显示一个对话框,询问用户是否真的想要出口。问题是无论用户选择哪个选项,程序都会关闭。

这是我尝试过的:

private void addActionWhenFrameIsClosed( )
{

    addWindowListener( new WindowAdapter( )
    {
        public void windowClosing( WindowEvent e )
        {
            if( isThereAnyThreadRunning( ) )
            {
                int dialogButton = JOptionPane.YES_NO_OPTION;
                int dialogResult = JOptionPane.showConfirmDialog( null, "There are some threads running... "
                                                                        + "\nAre you sure you want to exit?",
                                                                  "Warning", dialogButton );

                if( dialogResult == JOptionPane.YES_OPTION)
                {
                    dispose( );
                }

            }
        }
    } );
}

请尝试将这行代码添加为 addActionWhenFrameIsClosed

中的第一行

setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);