Using setBounds with jLayeredPane

I am trying to use setBounds with a jLayeredPane. For some reason the setBounds constraint does not work unless I add another component to the jFrame AFTER I add the jLayeredPane to my jFrame. For example, if my only component on my frame is a jLayeredPane, and I add it as follows:

this.add(layeredPane);

it does not work. The bounds fill the entire jFrame.

If I have other components before, such as:

this.add(jl);

this.add(layeredPane);

It still does not work. The layeredPane fills the entire JFrame and I cannot see the jl component.

Yet if I have:

this.add(layeredPane);

this.add(jl);

Then it works. The bounds works on the jLayeredPane.

Can someone explain to me why a component needs to be added AFTER I add the jLayeredPane for the bounds to work?

Attached is some code which I simplified which displays the problem:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

publicclass Mainextends JFrame

{

JLayeredPane layeredPane;

Component dragComponent;

int xAdjustment;

int yAdjustment;

public Main()

{

JLabel jl =new JLabel("Hello");

layeredPane =new JLayeredPane();

layeredPane.setLayout(null );

//layeredPane.setPreferredSize(new Dimension(300,300));

//layeredPane.setMaximumSize(new Dimension(400,400));

layeredPane.setBorder(BorderFactory.createLineBorder(Color.GREEN));

layeredPane.setBounds(50,50,600,500);

/** this is the line explained in my question **/

this.add(layeredPane);

}

publicstaticvoid main(String[] args)

{

JFrame frame =new Main();

frame.setDefaultCloseOperation( DISPOSE_ON_CLOSE );

frame.setSize(600, 600);

frame.setLocationRelativeTo(null );

frame.setVisible(true);

}

}

[2755 byte] By [Kojow777a] at [2007-11-27 11:29:34]
# 1

In the future Swing related questions should be posted in the Swing forum.

You need to do some reading on how Layout Managers work:

http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html

In your example the layered pane is using a null layout, but the frame is still using a BorderLayout by default.

So read the above tutorial to figure out how the BorderLayout works. You are adding a component to the center and by default this component will occupy all the space available which happens to be the size of your frame.

You can't add two components to the center of the BorderLayout so you get the unexpected behaviour you are seeing.

camickra at 2007-7-29 16:28:47 > top of Java-index,Java Essentials,Java Programming...
# 2

set the

frame.setLayout(null);

JL.Nayaka at 2007-7-29 16:28:47 > top of Java-index,Java Essentials,Java Programming...
# 3

Thanks for explaining it to me camickr, makes sense now. :)

Will post swing questions in Swing forum from now on.

Kojow777a at 2007-7-29 16:28:47 > top of Java-index,Java Essentials,Java Programming...