Question

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:

  1. Why is setBounds so important?
  2. 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 a JLayeredPane. (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.

Was it helpful?

Solution

Regarding:

  1. Why is setBounds so important: A JLayeredPane uses essentially a null layout, and whenever you use null layouts, you the coder are completely responsible for both the size and position of the components that you add. That's simply the rules of this layout.
  2. How to determine the appropriate bounds: One thing I've done is simply to let the component tell me what its preferredSize is and then use it for its size:

myJLabel.setSize(myJLabel.getPreferredSize());

Another thing I've done is to use non-opaque JPanels for each layer of my JLayeredPane, give these JPanels appropriate layouts and then add my components to the appropriate layer JPanel. I then use a listener to be sure that the layer JPanel's size matches that of its JLayeredPane container.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top