1

Can anybody tell me what is the difference between the below Code

JFrame jf=new JFrame();
JButton jb=new JButton();
jf.add(jb);

and

JFrame jf=new JFrame();
Container c=jf.getContentPane();
JButton jb=new JButton();
c.add(jb);

Even I am not Clear about the RootPane,LayeredPane,GlassPane. What is the use of RootPane?? I have never used it in my coding. I have read it from the below link

http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html

but not too much clear because there is no practical situation where I have used the above. Thanks for your answer!!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Jatin Khurana
  • 1,155
  • 8
  • 15

2 Answers2

1

As of Java 5, there is no difference between you code examples. JFrame#add is now redirected to JFrame#getContentPane on your behalf.

Before Java 5, it would throw an exception, which meant you had to add your components directly to the content pane yourself.

The JRootPane is used to provide a light weight container onto which other Swing components can be added. More importantly, it provides a means by which the top level Swing containers can organise themselves.

The JRootPane is made of layers. At the bottom is the JMenuBar and content pane and above that is the glass pane.

Because of the way it's constructed, the JRootPane can actually have a number of additional layers (typically between the content pane and the glass pane), this is typically used for things like popups.

The glass pane acts as a overlay which can be used to render content over the top of everything else (as well as block mouse and keyboard events).

Take a look at How to use Root Panes.

Normally, other then the content pane and glass pane, you wouldn't typically use any of the other parts of the root pane.

You could also take a look at this for a quick example of a glass pane in use

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

Both are same...
Both are added in java.awt.Container object.

JFrame and Container have following hierarchy
Case 1: JFrame#add()--> Frame#add()--> Window#add()--> Container#add() // Component add to container

Case 2: JFrame#getContentPane() --> getRootPane().getContentPane(); it will return Container object(Container#add)