Search code examples
swingjpaneljdesktoppane

Which components can be added in a JDesktopPane?


I'm having some trouble designing an MDI Application with Swing.

I have no trouble implementing the JDesktopPane & JInternalFrames, my question will be a little more specific. Here is my base container Frame in a glance:

package applicationGUI;

import javax.swing.JFrame;

public class DesktopContainer extends JFrame{
/* Fields */

/* Constructors */
    public DesktopContainer(){
        setContentPane(new Desktop());
        setJMenuBar(AppllicationMenuBar.getMenuBar());

    }
/* Public Methods */
    public Desktop getDesktop(){
        return (Desktop)getContentPane();
    }
}

And my Desktop:

public class Desktop extends JDesktopPane{}

Notice that I set a Desktop as a content pane of the DesktopContainer. What I want is, to be able to add JPanels on the Desktop (specificially, just below the JMenuBar). Unfortunately, I wasn't able to do this. And finally, here are my questions:

1-) Can JPanel objects be drawn on a JDesktopPane? I did some digging, I guess it has something to do with the JLayeredPane capabilities, but unfortunately I couldn't implement it.

2-) If JPanel object can't be drawn on a JDesktopPane, how can I manage to do what I want, any advice? I just figured, "add two JPanels to the JFrame, use the one on the top for your needs, and draw JDesktopPane into the second JPanel below". Is this a good approach?

Thank you for your answers..


Solution

  • A JPanel can be drawn and can receive events on a JDesktopPane

    public class DesktopContainer extends JFrame { 
    /* Constructors */
        public DesktopContainer(){
            setContentPane(new Desktop());
            setJMenuBar(createJMenuBar());
    
            APanel a = new APanel();
            a.setBounds(0, 0, 200, 200);
            a.setVisible(true);
            getDesktop().add(a);
        }   
        ....
    }
    
    class Desktop extends JDesktopPane {
    }
    
    class APanel extends JPanel { 
        public APanel() { 
            setLayout(new BorderLayout());
            add(new JButton("Hello stackoverflow"));
        }
    }
    

    It works fine. You should invoke setVisible(true), setBounds() on JPanel as JInternalFrame required.