Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parent for JDialog from JPanel

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.

like image 819
user1420504 Avatar asked May 27 '12 19:05

user1420504


People also ask

Where is JDialog used in an application?

JDialog is one of the important features of JAVA Swing contributing to interactive desktop-based applications. This is used as a top-level container on which multiple lightweight JAVA swing components can be placed to form a window based application.

What is the difference between JFrame and JDialog?

JFrame is a normal window with its normal buttons (optionally) and decorations. JDialog on the other side does not have a maximize and minimize buttons and usually are created with JOptionPane static methods, and are better fit to make them modal (they block other components until they are closed).

Can a JPanel contain JFrame?

These classes are imported and then used in many GUI applications. 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.


1 Answers

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.

like image 178
gmazlami Avatar answered Sep 22 '22 19:09

gmazlami