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?
We use the last, Graphics, to render visuals (e.g., figures, pictures, and even text) in a JPanel that contains the graphics part of a JFrame.
Just click on form and go to JFrame properties, then Code tab and check Generate Center .
Both JFrame and JPanel are important as a swing GUI cannot exist without these top-level containers. JFrame and JPanel both provide different methods to perform different GUI related functions.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With