JFrame On Close Operation

随声附和 提交于 2019-12-17 19:58:43

问题


I was wondering if there is a way, by clicking on the "X", to let the program perform some code before closing the JFrame. The setDefaultCloseOperation() method takes only an integer.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

回答1:


You might be interested in using a WindowListener. The WindowListener tutorial.




回答2:


this.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e){
                    int i=JOptionPane.showConfirmDialog(null, "Seguro que quiere salir?");
                    if(i==0)
                        System.exit(0);//cierra aplicacion
                }
            });



回答3:


@Jeffrey has a good answer, but you should consider what you're trying to do. If you really want to do something upon the closing of a frame, then a WindowListener is the way to go. However, if you're looking for a place to do some cleanup and graceful shutdown stuff, then you probably want a shutdown hook instead. Using a WindowListener, the code will only be triggered, as you said, by the user "clicking on the X". But what if the user starts the app in the foreground of a terminal and kills it with Ctrl+C? What if the user kills the process from the command line or from a task manager?



来源:https://stackoverflow.com/questions/10468149/jframe-on-close-operation

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