How can I close a JFrame by click on a button?

落花浮王杯 提交于 2019-12-23 18:53:14

问题


I would like to have a button in my window such that if I click it (button) the window is closed.

I found out that I can close a window in the following way:

referenceToTheFrame.hide(); //hides the frame from view
refToTheFrame.dispose(); //disposes the frame from memory

But if I do this way, compiler complains:

Note: myProgram.java uses or overrides a deprecated API
Note: Recompile with -Xlint:deprication for details.

Do I do something unsafe?


回答1:


The recommended way is to use:

referenceToTheFrame.setVisible(false)

The hide method is deprecated and should not longer be used. (Although internally setVisible will call hide or show)

Additionally if you want to dispose the frame, you have to call dispose manually. (In case you need the window-closed event for example) A call to setDefaultCloseOperation doesn't help you here, because it only affects the behavior after a click on the close button from the system menu.

See the Swing documentation for further information.




回答2:


DR has the correct answer. Regarding the compiler warnings: hide() is a deprecated call belonging to Window. Don't ever use it, stick with setVisible().




回答3:


Use dispose() on the frame object.



来源:https://stackoverflow.com/questions/2599993/how-can-i-close-a-jframe-by-click-on-a-button

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