Search code examples
javaswingjinternalframejdesktoppaneswingutilities

Add JInternalFrame to JDesktopPane using a button inside other JInternalFrame


This snippet code I got from https://stackoverflow.com/a/6868039/2240900

how to add the internal2 to desktoppane1 using a button placed somewhere in internal1.

In the ActionListener added to your button you can use code like the following to get a reference to the desktop pane:

Container container = SwingUtilities.getAncestorOfClass(JDesktopPane.class, (Component)event.getSource());

if (container != null)
{
    JDesktopPane desktop = (JDesktopPane)container;
    JInternalFrame frame = new JInternalFrame(...);
    desktop.add( frame );
} 

My question is how to add another JInternalFrame if the button reside in another JInternalFrame? ex: add internalX to desktoppane1 using a button placed somewhere in internal2/internal3/internalX, where each internal was created using a button inside internalX not using a menubar.

Any help will be appreciated. Thanks.


Solution

  • I accidentally find out that we can use a method of JInternalFrame that is getDesktopPane(). As mention in javadoc:

    getDesktopPane
    
        public JDesktopPane getDesktopPane()
    
    Convenience method that searches the ancestor hierarchy for a JDesktop instance. If JInternalFrame finds none, the desktopIcon tree is searched.
    
    Returns:
        the JDesktopPane this internal frame belongs to, or null if none is found
    

    So we can just use a command like:

    JDesktopPane desktopPane = internalFrame.getDesktopPane();
    desktopPane.add(internalX);
    

    or if the class extends JInternalFrame simply use

    JDesktopPane desktopPane = this.getDesktopPane();
    desktoppane.add(internalX);
    

    to get the JDesktopPane to add another JInternalFrame in a nested JInternalFrame.