Depending on what you intend to do with the ancestor, you may or may not need to cast it to JFrame (but it may be something else than a JFrame, so I wouldn't do the cast in code that doesn't know where the JPanel has been added).
Component topLevelAncestor = thePanel.getTopLevelAncestor(); // may return null
Darryl Burke wrote:It will work since getAncestorOfClass() uses Class#isInstance() and a sub class is an instance of the super class.sabre150 wrote:Won't work when, as in so many (usually bad) examples, the ancestor is actually an extended JFrame.
Assuming that the panel has been added to the component tree of a JFrame then
JFrame f = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, panel);