5

In my Swing app. I have a JFrame with few JPanels. One of it I use for placing another panels. And one of these - another panel - calls a JDialog. Constructor of dialog accepts Frame, String and Boolean as parameters. My problem is how to get parent (which is frame) from this panel?

SwingUtilities.windowForComponent(...) and SwingUtilities.getWindowAncestor(...) do not work in my case. Constructor with no parameters is not an option.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user1420504
  • 55
  • 1
  • 1
  • 4
  • Use the technique show [here](http://stackoverflow.com/a/10611286/418556). If you cannot make that work for your use-case, post an [SSCCE](http://sscce.org/) of your best attempt. – Andrew Thompson May 27 '12 at 19:44
  • 2
    @user1420504 Just to know, why doesn't `SwingUtilities.getWindowAncestor(...)` work in your case? – Timmos Mar 20 '13 at 15:58

2 Answers2

9

Every JComponent supports the Method getParent(). As the name of the method says, it returns you a reference to the parent of this component. Since JDialog, JPanel, JFrame etc. are Subclasses of JComponent, you can use it in your case. But be aware that you have to do a type cast, e.g. :

JFrame parentFrame = (JFrame) myContenPane.getParent()

And depending on your layout, you may have to call getParent() multiple times, which is quite ugly.

Hope this helps.

gmazlami
  • 684
  • 2
  • 9
  • 18
6

To get current panel parent you can use the following method:

(JFrame)this.getRootpane().getParent();
vinay
  • 1,121
  • 2
  • 12
  • 17