如何以编程方式关闭 JFrame [英] How to programmatically close a JFrame

查看:28
本文介绍了如何以编程方式关闭 JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JFrame 关闭的正确方法是什么,就像用户按下 X 关闭按钮或按下 Alt+F4(在 Windows 上)?

What's the correct way to get a JFrame to close, the same as if the user had hit the X close button, or pressed Alt+F4 (on Windows)?

我的默认关闭操作设置为我想要的方式,通过:

I have my default close operation set the way I want, via:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

它完全符合我对上述控件的要求.这个问题与此无关.

It does exactly what I want with the aforementioned controls. This question isn't about that.

我真正想做的是使 GUI 的行为与按下 X 关闭按钮的行为相同.

What I really want to do is cause the GUI to behave in the same way as a press of X close button would cause it to behave.

假设我要扩展 WindowAdaptor,然后通过 addWindowListener() 添加我的适配器实例作为侦听器.我想通过 windowDeactivated()windowClosing()windowClosed() 看到与 windowClosed() 相同的调用序列code>X 关闭按钮.与其说是撕毁窗户,不如说是告诉它撕毁自己,可以这么说.

Suppose I were to extend WindowAdaptor and then add an instance of my adaptor as a listener via addWindowListener(). I would like to see the same sequence of calls through windowDeactivated(), windowClosing(), and windowClosed() as would occur with the X close button. Not so much tearing up the window as telling it to tear itself up, so to speak.

推荐答案

如果您希望 GUI 的行为就像您单击了 X 关闭按钮,那么您需要将窗口关闭事件分派给<代码>窗口.ExitAction 来自 关闭应用程序 允许您将此功能添加到菜单项或任何易于使用 Action 的组件.

If you want the GUI to behave as if you clicked the X close button then you need to dispatch a window closing event to the Window. The ExitAction from Closing An Application allows you to add this functionality to a menu item or any component that uses Actions easily.

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

这篇关于如何以编程方式关闭 JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆