Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 554
scravy Avatar asked Mar 10 '12 22:03

scravy


People also ask

Can a JPanel contain JFrame?

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.

How do you make a JFrame appear in the middle of the screen?

Just click on form and go to JFrame properties, then Code tab and check Generate Center .

Does JPanel need JFrame?

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.


1 Answers

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); 
like image 122
Hovercraft Full Of Eels Avatar answered Oct 13 '22 06:10

Hovercraft Full Of Eels