Java/Swing: Obtain Window/JFrame from inside a JPanel

scravy picture scravy · Mar 10, 2012 · Viewed 77.9k times · Source

How can I get the JFrame in which a JPanel is living?

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?

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Mar 10, 2012

You could use SwingUtilities.getWindowAncestor(...) method that will return a Window that you could cast to your top level type.

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