Java / Swing: get window / JFrame from inside JPanel

How can I get the JFrame that JPanel lives in?

My current solution is to ask the panel for it to be the parent (etc.) until I find the 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 could be?

+56
java swing jframe
Mar 10 2018-12-12T00:
source share
4 answers

You can use the SwingUtilities.getWindowAncestor(...) method, which will return a Window that you can apply to your top-level type.

 JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this); 
+109
Mar 10 2018-12-12T00:
source share
 JFrame frame = (JFrame)SwingUtilities.getRoot(x); 
+29
Mar 10 2018-12-12T00:
source share

There are two direct, different methods in SwingUtilities that provide the same functionality (as stated in their Javadoc). They return java.awt.Window , but if you added your panel to the JFrame , you can safely refer it to the JFrame .

Two simple and easy 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(); 
+23
Aug 05
source share

As other commentators have already noted, this is usually not true for a simple translation in JFrame. This works in most special cases, but I believe that the only correct answer is f3 from icza in https://stackoverflow.com/a/3/9298/

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

because it is valid and safe casting and is almost as simple as all the other answers.

+1
Nov 08 '16 at 10:28
source share



All Articles