Java/Swing:从 JPanel 内部获取 Window/JFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9650874/
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
Java/Swing: Obtain Window/JFrame from inside a JPanel
提问by scravy
How can I get the JFrame in which a JPanel is living?
如何获得 JPanel 所在的 JFrame?
My current solution is to ask the panel for it's parent (and so on) until I find a Window:
我目前的解决方案是向面板询问它的父级(等等),直到我找到一个窗口:
Container parent = this; // this is a JPanel
do {
parent = parent.getParent();
} while (!(parent instanceof Window) && parent != null);
if (parent != null) {
// found a parent Window
}
Is there a more elegant way, a method in the Standard Library may be?
有没有更优雅的方法,标准库中的方法可能是?
采纳答案by Hovercraft Full Of Eels
You could use SwingUtilities.getWindowAncestor(...)
method that will return a Window that you could cast to your top level type.
您可以使用SwingUtilities.getWindowAncestor(...)
将返回一个可以转换为顶级类型的 Window 的方法。
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
回答by Ismael Abreu
JFrame frame = (JFrame)SwingUtilities.getRoot(x);
回答by icza
There are 2 direct, different methods for this in SwingUtilities
which provide the same functionality (as noted in their Javadoc). They return java.awt.Window
but if you added your panel to a JFrame
, you can safely cast it to JFrame
.
有两种直接的、不同的方法SwingUtilities
可以提供相同的功能(如他们的 Javadoc 中所述)。它们会返回,java.awt.Window
但如果您将面板添加到 a JFrame
,则可以安全地将其投射到JFrame
.
The 2 direct and most simple ways:
2种直接和最简单的方法:
JFrame f1 = (JFrame) SwingUtilities.windowForComponent(comp);
JFrame f2 = (JFrame) SwingUtilities.getWindowAncestor(comp);
For completeness some other ways:
为了完整起见,还有一些其他方式:
JFrame f3 = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, comp);
JFrame f4 = (JFrame) SwingUtilities.getRoot(comp);
JFrame f5 = (JFrame) SwingUtilities.getRootPane(comp).getParent();
回答by jan
As other commentators already mentioned it is not generally valid to simply cast to JFrame
. That does work in most special cases, but I think the only correct answer is f3
by icza in https://stackoverflow.com/a/25137298/1184842
正如其他评论员已经提到的那样,简单地强制转换为JFrame
. 这在大多数特殊情况下都有效,但我认为唯一正确的答案是https://stackoverflow.com/a/25137298/1184842 中f3
的 icza
JFrame f3 = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, comp);
because this is a valid and safe cast and nearly as simple as all other answers.
因为这是一个有效且安全的转换,几乎与所有其他答案一样简单。