80

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

4 回答 4

154

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

JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
于 2012-03-10T22:55:42.797 回答
43

有 2 种直接的、不同的方法SwingUtilities可以提供相同的功能(如其 Javadoc 中所述)。它们返回java.awt.Window,但如果您将面板添加到 a 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();
于 2014-08-05T11:06:19.537 回答
30
JFrame frame = (JFrame)SwingUtilities.getRoot(x);
于 2012-03-10T22:59:23.670 回答
4

正如其他评论员已经提到的那样,简单地转换为JFrame. 这在大多数特殊情况下确实有效,但我认为唯一正确的答案是https://stackoverflow.com/a/25137298/1184842f3中的 icza

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

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

于 2016-11-08T10:28:27.080 回答