Search code examples
javaswinglayout-managerjcomponentjmenubar

The JPanel contentpane confusion


I am learning Java Swing and I appended a menuBar to the frame. By default this should call jframe.getContentPane().add(child). When I ran the script the menuBar didn't show up. But the button was at the very top "y=0" if that makes sense.

Then I realized my mistake I actually had to put in a menu in the menubar. Then the menuBar showed up. So that got me thinking...is the "menubar" "contentpane" actually 2 panels? It is confusing the hell out of me. Because that acted a lot like a panel. But getContentPane() returns a Container, not a JPanel object so I'm confused.

If so, does that mean that the only thing that is dumped directly into a frame are just Jpanel objects? Hence JButtons, JLabels are not directly in a frame... Does that mean, jpanels are "nested"? One more thing that is confusing me. If a jpanel can control how things are positioned, what is a LayoutManager for? :S Thanks, and please answer as if to a 2yr old asking why the sky is blue,ha ;)


Solution

  • Some random thoughts:

    • Yes, JPanels and other components are often "nested". This is where a firm understanding of the Swing/AWT layout managers is essential.
    • While the type returned by a JFrame's getContentPane() is technically a Container, it's also a JPanel (which inherits eventually from Container).
    • I believe that you can make anything that derives from Container the contentPane, but you need to take care that it is opaque.