简体   繁体   English

从面板上关闭框架

[英]Closing a Frame from a Panel

Let me first explain the situation, I have a class with a JPanel called panelclass. 让我先解释一下情况,我有一个带有JPanel的类,名为panelclass。 It's method getPanel() returns the JPanel. 它的方法getPanel()返回JPanel。

In a JFrame class called frameclass, I create a new object of panelclass, got its panel and added it to the frame pane. 在一个名为frameclass的JFrame类中,我创建一个panelclass的新对象,获取其面板并将其添加到框架窗格中。

What I am trying to achieve is, when a button in paneclass is clicked, It should close this JFrame ie.frameclass. 我想要实现的是,当单击paneclass中的按钮时,它应该关闭此JFrame ie.frameclass。 I donot know how a panelclass can communicate back to the frameclass to close. 我不知道面板类如何可以与框架类进行通信以关闭。 I tried this.dispose() and super.dispose() but was not successful even after extending JFrame 我尝试了this.dispose()和super.dispose()但即使扩展了JFrame也没有成功

Is there a simpler way? 有没有更简单的方法? Please do help. 请帮忙。

There are a few was to achieve this, but the simplest is probably through the use of SwingUtilities.getWindowAncestor(Component) 有一些方法可以实现此目的,但最简单的方法可能是通过使用SwingUtilities.getWindowAncestor(Component)

This will return the Window that the component was added to or null if it has no parent window. 这将返回添加了组件的Window ;如果没有父窗口,则返回null From there you can simply call Window#dispose to close the frame. 从那里您可以简单地调用Window#dispose来关闭框架。

when a button in paneclass is clicked, It should close this JFrame 单击paneclass中的按钮时,应关闭此JFrame

See Closing an Application . 请参阅关闭应用程序 I prefer using something like the `ExitAction' described there. 我更喜欢使用此处描述的“ ExitAction”之类的东西。 The reason is that your application will behave just like the user clicked on the close button of the frame which means that if you have any WindowListeners added to the window they will be invoked. 原因是您的应用程序的行为就像用户单击框架的关闭按钮一样,这意味着如果您在窗口中添加了任何WindowListener,它们将被调用。

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

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