Java/Swing:从JPanel内部获取Window/JFrame

Java/Swing:从JPanel内部获取Window/JFrame,java,swing,jframe,swingutilities,Java,Swing,Jframe,Swingutilities,如何获得JPanel所在的JFrame 我当前的解决方案是,在找到一个窗口之前,向面板询问它的父对象(等等): Container parent = this; // this is a JPanel do { parent = parent.getParent(); } while (!(parent instanceof Window) && parent != null); if (parent != null) { // found a parent Wi

如何获得JPanel所在的JFrame

我当前的解决方案是,在找到一个窗口之前,向面板询问它的父对象(等等):

Container parent = this; // this is a JPanel
do {
    parent = parent.getParent();
} while (!(parent instanceof Window) && parent != null);
if (parent != null) {
    // found a parent Window
}

有没有更优雅的方法,标准库中的方法可能是?

您可以使用
SwingUtilities.getWindowSenents(…)
方法,该方法将返回一个可以强制转换为顶级类型的窗口

JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);

SwingUtilities
中有两种直接、不同的方法提供相同的功能(如Javadoc中所述)。它们返回
java.awt.Window
,但如果将面板添加到
JFrame
,则可以安全地将其强制转换到
JFrame

两种最直接、最简单的方法:

JFrame f1 = (JFrame) SwingUtilities.windowForComponent(comp);
JFrame f2 = (JFrame) SwingUtilities.getWindowAncestor(comp);
JFrame f3 = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, comp);
JFrame f4 = (JFrame) SwingUtilities.getRoot(comp);
JFrame f5 = (JFrame) SwingUtilities.getRootPane(comp).getParent();
对于完整性,还有其他一些方法:

JFrame f1 = (JFrame) SwingUtilities.windowForComponent(comp);
JFrame f2 = (JFrame) SwingUtilities.getWindowAncestor(comp);
JFrame f3 = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, comp);
JFrame f4 = (JFrame) SwingUtilities.getRoot(comp);
JFrame f5 = (JFrame) SwingUtilities.getRootPane(comp).getParent();

正如其他评论员已经提到的,简单地转换到
JFrame
通常是无效的。这在大多数特殊情况下都是有效的,但我认为唯一正确的答案是icza年的
f3


因为这是一个有效且安全的转换,几乎与所有其他答案一样简单。

Javadoc声明这可能是一个
Applet
(而不是
窗口或
框架
)。有效。哦,装满鳗鱼的气垫船,你知道很多隐藏的东西。