javaswingjframeswingutilities

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


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?


Solution

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