java JFrame 捕获处置事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4154780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JFrame catch dispose event
提问by Andrej
I have a Java project.
I have a JFrame with a handler attached to it like so
我有一个 Java 项目。
我有一个带有处理程序的 JFrame,就像这样
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
this.setEnabled(true);
}
});
But, on that frame I also have a close button (to make it more user friendly) and that "close" button calls the frame dispose method. Now, when I close the frame by clicking the little x button on the top right corner, the WindowListener is called. But the event doesn't fire when I invoke the dispose method.
should I Invoke some other method to close, so the WindowListener fires, or maybe implement another listener?
但是,在那个框架上,我还有一个关闭按钮(以使其更加用户友好)并且该“关闭”按钮调用框架处理方法。现在,当我通过单击右上角的小 x 按钮关闭框架时,将调用 WindowListener。但是当我调用 dispose 方法时事件不会触发。
我应该调用一些其他方法来关闭,以便 WindowListener 触发,或者可能实现另一个侦听器?
采纳答案by camickr
on that frame i also have a close button (to make it more user friendly)
在那个框架上,我还有一个关闭按钮(使其更加用户友好)
Check out the Closing an Applicationsolution to handle this. All you really need to do is add the "ExitAction" to your button, but you can use the whole approach if you want.
查看关闭应用程序解决方案来处理这个问题。您真正需要做的就是将“ExitAction”添加到您的按钮中,但您可以根据需要使用整个方法。
回答by cbaldan
I spent days searching for a solution to the same issue as the OP.
我花了几天时间寻找与 OP 相同问题的解决方案。
It was hiding in plain sight.
The windowClosed()
method is called if the frame is closed by the Xbutton or if myFrame.dispose()
method is called.
它隐藏在显眼的地方。该windowClosed()
帧是否通过关闭方法被称为X按钮,或者如果myFrame.dispose()
方法被调用。
JFrame myFrame = new JFrame();
myFrame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosed(java.awt.event.WindowEvent windowEvent) {
// your code
}
});
来源:https: //alvinalexander.com/blog/post/jfc-swing/closure-your-java-swing-application-when-user-presses-close-but