How can I stop the closing of a Java application

十年热恋 提交于 2020-01-03 19:04:27

问题


I have a Java Desktop application and I would like when the user selects Exit to get a pop-up window that asks him if he wants to proceed with closing the application or not. I know how to make the window come up and read the user's response but what I need to know is how I can stop the application from closing (something like System.close().cancel()).

Is that possible?


回答1:


Yes it is possible.

After calling setDefaultCloseOperation(DO_NOTHING_ON_CLOSE), add a WindowListener or WindowAdapter and in the windowClosing(WindowEvent) method, pop a JOptionPane.

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



回答2:


You can add a window listener. (Note: WindowAdapter is in the java.awt.event package)

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



回答3:


After setting the setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); to your JFrame or JDialog, add a windows listener :

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 {

            }
        }
    });



回答4:


On your JFrame, you have to set a defaultCloseOperation:

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

Then set your pop-up's closing operation to EXIT_ON_CLOSE.



来源:https://stackoverflow.com/questions/8469097/how-can-i-stop-the-closing-of-a-java-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!