2

I am trying to add a JPanel (well, several) to a JLayeredPane. However, when I do so, the paint component method of the JPanel seems to have no effect. An example is included below:

import javax.swing.*;
import java.awt.*;

public class Example {

    public static void main(String[] args) {

        // This Works as expected
        JFrame usingPanel = new JFrame();
        JPanel p = new JPanel();
        p.add(new BluePanel());
        usingPanel.setContentPane(p);
        usingPanel.pack();
        usingPanel.setVisible(true);

        // This makes the frame but does not paint the BluePanel
        JFrame usingLayer = new JFrame();
        JLayeredPane l = new JLayeredPane();
        l.setPreferredSize(new Dimension(200,200));
        l.add(new BluePanel(), JLayeredPane.DEFAULT_LAYER);
        JPanel p2 = new JPanel();
        p2.add(l);
        usingLayer.setContentPane(p2);
        usingLayer.pack();
        usingLayer.setVisible(true);
    }


   static class BluePanel extends JPanel{

        public BluePanel(){
            setPreferredSize(new Dimension(200,200));
        }

        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(Color.BLUE);
            g.fillRect(0, 0, 200, 200);
        }


    }


}

Why is this? and what are the possible solutions?

James
  • 2,483
  • 2
  • 24
  • 31

2 Answers2

8

JLayeredPane does not have a LayoutManager, so you need to set the location and size of your panels yourself. See the tutorial

Walter Laan
  • 2,956
  • 17
  • 15
1
  1. you hardcoded the size on the screen and have to change from

    g.fillRect(0, 0, 200, 200);
    

    to

    g.fillRect(0, 0, getWidth(), getHeight());
    
  2. (a minor change) add the method

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }
    

    and then remove of code line setPreferredSize(new Dimension(200,200));

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
mKorbel
  • 109,525
  • 20
  • 134
  • 319