简体   繁体   English

JFrame关闭操作

[英]JFrame On Close Operation

I was wondering if there is a way, by clicking on the "X", to let the program perform some code before closing the JFrame. 我想知道是否有一种方法,通过单击“ X”,让程序在关闭JFrame之前执行一些代码。 The setDefaultCloseOperation() method takes only an integer. setDefaultCloseOperation()方法仅采用整数。

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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
                }
            });

@Jeffrey has a good answer, but you should consider what you're trying to do. @Jeffrey的回答很不错,但是您应该考虑自己要做什么。 If you really want to do something upon the closing of a frame, then a WindowListener is the way to go. 如果您确实想在关闭框架时执行某项操作,则可以使用WindowListener。 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". 如您所说,使用WindowListener只能由用户“单击X”来触发代码。 But what if the user starts the app in the foreground of a terminal and kills it with Ctrl+C? 但是,如果用户在终端的前台启动该应用程序并用Ctrl + C终止该应用程序怎么办? What if the user kills the process from the command line or from a task manager? 如果用户从命令行或任务管理器中终止进程怎么办?

You might be interested in using a WindowListener . 您可能对使用WindowListener感兴趣。 The WindowListener tutorial . WindowListener教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM