如何停止关闭Java应用程序

时间:2011-12-12 01:47:16

标签: java swing user-interface windowlistener

我有一个Java桌面应用程序,我希望当用户选择“退出”时会弹出一个窗口,询问他是否要继续关闭应用程序。我知道如何让窗口出现并读取用户的响应,但我需要知道的是如何阻止应用程序关闭(类似System.close().cancel())。

这可能吗?

4 个答案:

答案 0 :(得分:7)

是的,这是可能的。

致电setDefaultCloseOperation(DO_NOTHING_ON_CLOSE)后,添加WindowListenerWindowAdapter,然后在windowClosing(WindowEvent)方法中点击JOptionPane

int result = JOptionPane.showConfirmDialog(frame, "Exit the application?");
if (result==JOptionPane.OK_OPTION) {
    System.exit(0);     
}

答案 1 :(得分:1)

您可以添加窗口侦听器。 (注意:WindowAdapter位于java.awt.event包中)

myframe.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
        // do something
    }
});

答案 2 :(得分:1)

setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);设置为JFrame或JDialog后,添加一个Windows侦听器:

addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent arg0) {
            int result = JOptionPane.showConfirmDialog((Component) null, "Do u really want to exit ?!",
                    "Confirmation", JOptionPane.YES_NO_OPTION);
            if (result == 0) {
                System.exit(0);
            } else {

            }
        }
    });

答案 3 :(得分:0)

JFrame上,您必须设置defaultCloseOperation

JFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

然后将弹出窗口的关闭操作设置为EXIT_ON_CLOSE