Java/Swing: Obtain Window/JFrame from inside a JPanel
Asked Answered
M

4

89

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?

Maccabees answered 10/3, 2012 at 22:47 Comment(0)
S
167

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);
Spirituality answered 10/3, 2012 at 22:55 Comment(1)
That worked. You know much that is hidden, O Hovercraft Full Of Eels.Shaneka
B
45

There are 2 direct, different methods for this in SwingUtilities which provide the same functionality (as noted in their Javadoc). They return java.awt.Window but if you added your panel to a JFrame, you can safely cast it to JFrame.

The 2 direct and most simple ways:

JFrame f1 = (JFrame) SwingUtilities.windowForComponent(comp);
JFrame f2 = (JFrame) SwingUtilities.getWindowAncestor(comp);

For completeness some other ways:

JFrame f3 = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, comp);
JFrame f4 = (JFrame) SwingUtilities.getRoot(comp);
JFrame f5 = (JFrame) SwingUtilities.getRootPane(comp).getParent();
Bock answered 5/8, 2014 at 11:6 Comment(0)
E
30
JFrame frame = (JFrame)SwingUtilities.getRoot(x);
Elam answered 10/3, 2012 at 22:59 Comment(1)
Javadoc states that this might be an Applet (not Window or Frame).Bock
N
6

As other commentators already mentioned it is not generally valid to simply cast to JFrame. That does work in most special cases, but I think the only correct answer is f3 by icza in https://mcmap.net/q/235897/-java-swing-obtain-window-jframe-from-inside-a-jpanel

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

because this is a valid and safe cast and nearly as simple as all other answers.

Newfeld answered 8/11, 2016 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.