Question

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.

Was it helpful?

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.

OTHER TIPS

Externalize the listener into it's own class, with proper parameters if needed. Then, you can instantiate this listener every time you create a new frame and apply it to its button.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top