Jatin Khurana
Jatin Khurana

Reputation: 1175

Why there are too much layering in the Container in the swing?

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!!

Upvotes: 1

Views: 87

Answers (2)

Rajeshkumar Natarajen
Rajeshkumar Natarajen

Reputation: 41

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)

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347332

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

Upvotes: 1

Related Questions