Java: How to nest JPanel in a GridLayout?

Viewed 825

I want to know how to nest JPanels using a GridLayout. This is how it should look like.

enter image description here

I approached this problem by 2 ways so far,

  • using JPanels and
  • using JLabels,

and none of them worked (only the first panel created is shown).

Here is the code for the JPanel approach:

    int x=20, y=20;
    JPanel [] panels = new JPanel[3];
    JLabel animal = new JLabel(new ImageIcon(getClass().getResource("Pictures/animal.gif")));
    JLabel map = new JLabel(new ImageIcon(getClass().getResource("Pictures/map.gif")));
    JLabel mountain = new JLabel(new ImageIcon(getClass().getResource("Pictures/mountain.gif")));

    for(int i=0;i<panels.length;i++)
    {
        if(i>0)
        {
            x+=x;
            y+=y;
        }
        panels[i] = new JPanel(new GridLayout(2,2));
        panels[i].setPreferredSize(new Dimension(x,y));

        if(i==0)
            panels[i].add(new JPanel());

        else
            panels[i].add(panels[i-1]);

        panels[i].add(mountain);
        panels[i].add(map);
        panels[i].add(animal);
    }       
    add(panels[2]);
2 Answers
Related