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?
You could use
SwingUtilities.getWindowAncestor(...)
method that will return a Window that you could cast to your top level type.There are 2 direct, different methods for this in
SwingUtilities
which provide the same functionality (as noted in their Javadoc). They returnjava.awt.Window
but if you added your panel to aJFrame
, you can safely cast it toJFrame
.The 2 direct and most simple ways:
For completeness some other ways:
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 isf3
by icza in https://stackoverflow.com/a/25137298/1184842because this is a valid and safe cast and nearly as simple as all other answers.