Java/Swing:如何从JPanel中获取Window/JFrame

86

如何获取包含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
}

是否有更优雅的方法,也许是标准库中的一个方法?

4个回答

163

您可以使用SwingUtilities.getWindowAncestor(...)方法,它将返回一个窗口(Window),您可以将其转换为您的顶级类型。

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

5
好的。荷载满载着鳗鱼的气垫船,你知道许多隐藏的东西,这很有效。 - user64141

44

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

这2种直接和最简单的方式:

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();

30
JFrame frame = (JFrame)SwingUtilities.getRoot(x);

6
Javadoc中指出这可能是一个“Applet”(而不是“Window”或“Frame”)。 - icza

6

正如其他评论者已经提到的那样,简单地将其转换为 JFrame 是不一定有效的。在大多数特殊情况下这确实可以工作,但我认为唯一正确的答案是 f3 ,由 icza 在 https://dev59.com/KGkw5IYBdhLWcg3wx9iC#25137298 中给出。

JFrame f3 = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, comp);

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接