JPanel inside another

anvd picture anvd · Jan 20, 2011 · Viewed 19.3k times · Source

I have a problem with a JPanel inside another one. I don't know why, but the result is a simple square, but the dimensions aren't correct. Why is that?

import java.awt.Color;
import java.awt.Container;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class jj extends JFrame {

    private JPanel painel3;
    private JPanel painel5;
    private Container container;

    public jj() {

        container = getContentPane();
        container.setLayout(null);

        painel5 = new JPanel();
        painel5.setBackground(Color.red);
        painel5.setBounds(120, 110, 100, 120);
        painel3 = new JPanel();
        painel3.setBackground(Color.white);
        painel3.add(painel5);
        painel3.setBounds(50, 50, 290, 220);

        container.add(painel3);

        // frame
        setSize(1000, 900);
        setLocation(200, 50);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {
        new jj();
    }
}

Answer

Jonas picture Jonas · Jan 20, 2011

You need to set the layout for panel3 also to null otherwise the default FlowLayout is used:

panel3.setLayout(null);