Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ;)

like image 657
Lews Therin Avatar asked Oct 13 '11 18:10

Lews Therin


People also ask

Is ContentPane a JPanel?

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.

What is JPanel Swing Java?

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.

How many panes or Jpanels can be placed in another pane or JPanel )?

D. Yes, but only one JPanel may be placed inside another.

What is setContentPane in Java?

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.


2 Answers

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.
like image 157
Hovercraft Full Of Eels Avatar answered Nov 06 '22 18:11

Hovercraft Full Of Eels


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

like image 32
mKorbel Avatar answered Nov 06 '22 20:11

mKorbel