如何设置关闭按钮的动作?
我在 Netbeans 6.9 中创建了一个独立的 java 桌面应用程序。我想设置应用程序的关闭按钮的操作。我想知道如何以及在哪里设置该关闭按钮的操作代码。有人可以帮我解决这个问题吗?
I've created a stand-alone java desktop application in Netbeans 6.9. I want to set the action for the close button of my application. I want to know how and where to set the code for the action of that close button. Can anyone please help me regarding this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您必须在关闭按钮上注册一个 ActionListener。在此侦听器中,您可以定义要执行的操作。
如何在 Java Swing 中将 ActionListener 添加到 JButton
You have to register an ActionListener on your close button. In this listener you can define what do to.
How add ActionListener to JButton in Java Swing
我认为 How to close a java swing application from the code 的答案也会有帮助
I think answers for How to close a java swing application from the code will be helpful too
右键单击该按钮,然后
>活动>行动>已执行操作。
NetBeans
将为您生成操作侦听器:)编辑:如果您想要一个关闭侦听器,请阅读 此处。
Right-click on the button then,
> Events > Action > actionPerformed
.NetBeans
will generate the action listener for you:)Edit: If you want a close listener, then read here.
一旦处理程序开始工作,一种方便的方法是“通过调用
setDefaultButton()
顶级容器根窗格上的方法。"请参阅教程部分如何使用 JButton 功能了解详情。Once you have the handler working, one convenient approach is to "set the default button by invoking the
setDefaultButton()
method on a top-level container's root pane." See the tutorial section How to Use JButton Features for details.我不喜欢唤醒僵尸,但是,这就是我要做的(考虑到您正在基于 Window 的应用程序中工作,否则这将毫无用处!):
显然,我正在谈论的窗口侦听器将转到您(作为用户)应该关闭的最后一个窗口,如果您希望它在最后一个窗口已关闭,但没有指定执行此操作的顺序,一些解决方法是使所有窗口共享一个标志/计数器以指示是否是时候删除临时文件/文件夹。
如果您的应用程序有时要在地下运行(我的意思是您可以在不关闭应用程序的情况下处理所有窗口),或者是一个守护进程,则这将不起作用
I dislike to wake up the zombies but, here is what I would do (this is considering that you are working in a Window based application, otherwise this is going to be useless!!!):
Obviously the window listener I'm talking about would go on the last window you (as a user) should close, this would not work either if you want it to happen when the last window is closed, but there is not an order specified to do that, some workarounds for that is making all your windows to share a flag/counter to indicate if it is time to delete the temp files/folders.
Again if your application is going to work underground sometimes (I mean that you can dispose all windows without shutting down the application), or is a daemon this won't work
如果您只想在按下关闭按钮时退出应用程序,可以
按照 Oracle教程
If you just want to exit the application when the close button is hit, you can use
as explained in the Oracle tutorial