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.
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.
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).
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.
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.
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