Pedro Romano Barbosa
Pedro Romano Barbosa

Reputation: 647

Adding a JLayeredPane to a JPanel

Im trying to insert a JLayeredPane to JPanel. When I insert the JLayeredPane to the frame, the components show and everything is okay, but when I insert the JLayeredPane to the JPanel and then insert the JPanel to the frame It doesn't display the JLayeredPane.

My code:

button1.setBounds(0, 0, 100, 100);
button2.setBounds(50, 50, 100, 100);
layer.add(button1,1);
layer.add(button2,0);
panel.add(layer);
this.add(panel);
this.setVisible(true);

Upvotes: 1

Views: 1304

Answers (1)

camickr
camickr

Reputation: 324207

I insert the JLayeredPane to the JPanel and then insert the JPanel to the frame It doesn't display the JLayeredPane.

A JPanel uses a FlowLayout which respects the preferred size of any component added to it.

A JLayeredPane does not use a layout manager and therefore does not have a preferred size so it is not displayed on the panel.

the components show and everything is okay,

The frame which uses a BorderLayout. The default location is the "CENTER" and the center will size the layered pane based on the space available in the frame.

There is no need for the extra overhead of adding the layered pane to the panel and then the panel to the frame.

Read the section from the Swing tutorial on How to Use Layered Panes for more information and working examples.

Upvotes: 3

Related Questions