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 ;)
Reason: Restrictions on Container. getContentPane() returns a Container object. This isn't really a plain Container object, but is actually a JPanel ! This is a Container as a consequence of the hierarchy.
JPanel, a part of the Java Swing package, is a container that can store a group of components. The main task of JPanel is to organize components, various layouts can be set in JPanel which provide better organization of components, however, it does not have a title bar.
D. Yes, but only one JPanel may be placed inside another.
setContentPane(Container c) : sets the ContentPane property of the window. getContentPane() : get the container which is the ContentPane for this Window. add(Component c): adds component to the Window.
Some random thoughts:
getContentPane()
is technically a Container, it's also a JPanel (which inherits eventually from Container). for that there is method
frame.setJMenuBar(menuBar);
for todays Java Swing GUI, is not neccesary declare ContentPane
, from Java5, and with BorderLayout as default LayoutManager
then frame.add(myPanel);
//is same as frame.add(myPanel, BorderLayout.CENTER)
and occupated whole Container
basic stuff about how to use LayourManagers
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