I was trying out JLayeredPane. So, in the following code, I created a JLayeredPane
and a JLabel
. I added the label to the layered pane, which I added to a JPanel
. This panel was then added to a JFrame.
public static void main(String[] args) {
frame = new JFrame("LayeredPane Example");
frame.setPreferredSize(new Dimension(500,500));
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(400, 400));
JLabel label = new JLabel("Label on LayeredPane");
label.setLocation(200, 200);
System.out.println("Width " + label.getWidth() );
label.setBounds(20, 20, 400, 40);
layeredPane.add(label);
layeredPane.setLayer(label, 10, 1);
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.add(layeredPane);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
Now the problem is that if I do not have the statement label.setBounds(20, 20, 400, 40);
, then the label does not appear on the layered pane. This raises two questions:
- Why is
setBounds
so important? - Probably a part of my previous questions answer, the label had an initial height and width of 0 before setting bounds, which might be the reason
setBounds
is important. In that case, I want to know how can I determine appropriate bounds for a Swing component when I am adding it to aJLayeredPane
. (If my bounds are less than the appropriate size of the component, the component will appear hidden)
Edit: The first question was answered earlier in more detail here.