java 有没有办法在Java中获得对当前帧的引用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4868852/
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
Is there any way to get a reference to the current frame in Java?
提问by LOD121
I have a menu bar class (MenuBarGUI) that I have put in all of my other classes and I need to know if I can close the current JFrame that it is contained in through an option in the menu. Normally I could call setVisible(false) then dispose() but because the menu bar doesn't have a reference to the current frame, I can't do that. Is there any way to do this?
我有一个菜单栏类 (MenuBarGUI),我已经把它放在了我所有的其他类中,我需要知道是否可以通过菜单中的选项关闭它所包含的当前 JFrame。通常我可以调用 setVisible(false) 然后调用 dispose() 但因为菜单栏没有对当前帧的引用,我不能这样做。有没有办法做到这一点?
采纳答案by Gursel Koca
if your MenuBarGUI class extends JMenuBar, you can use getTopLevelAncestormethod to get menu bar's window.
如果您的 MenuBarGUI 类扩展了 JMenuBar,您可以使用getTopLevelAncestor方法来获取菜单栏的窗口。
回答by jzd
getParent()
will get the parent container. With this method you will have to do some casting. A more ideal option would be to have the menu bar could take an interface that includes a close method.
getParent()
将获得父容器。使用这种方法,您将不得不进行一些铸造。更理想的选择是让菜单栏可以采用包含关闭方法的界面。
Here is an example:
下面是一个例子:
JFrame frame = new JFrame();
JMenuBar bar = new JMenuBar();
frame.setJMenuBar(bar);
if(bar.getParent().getParent().getParent() instanceof JFrame){
System.out.println(bar.getParent().getParent().getParent());
}
回答by Mark of Zorro
None of the above approaches worked for me.
以上方法都不适合我。
Since I only need the immediate parent of a panel, accessed them directly through a super call: super.setTitle("The new Frame Title"), etc.
由于我只需要面板的直接父级,因此可以通过超级调用直接访问它们:super.setTitle("The new Frame Title") 等。