Java: How to embed JPanel in GridLayout?

I want to know how to invest JPanelusing GridLayout. Here's how it should look.

enter image description here

I have approached this issue in two ways so far,

  • using JPaneland
  • using JLabels,

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

Here is the code for the approach JPanel:

    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]);
+4
source share
2 answers

- , , . , , - , . , - ( ):

 class GridPanel extends JPanel{

    JLabel mountain, map, animal;

    public GridPanel(JPanel panel){
        super();
        setLayout(new GridLayout(2, 2));
        animal = new JLabel(new ImageIcon(getClass().getResource("pictures/animal.gif")));
        map = new JLabel(new ImageIcon(getClass().getResource("pictures/map.gif")));
        mountain = new JLabel(new ImageIcon(getClass().getResource("pictures/mountain.gif")));
        add(panel);
        add(mountain);
        add(map);
        add(animal);
    }

}

, , . coud . , , :

   JPanel grid = new GridPanel(new JPanel()); //initial
    for(int i = 1; i <= 5; i++){
        grid = new GridPanel(grid);
    }
    add(grid);

JPanel. . .., , .. . 5 .

, ImageIO . , BufferedImage, , :

  BufferedImage mointainImg = ImageIO.read(new File("pictures/mountain.gif"));

JLabel, :

  mountain = new JLabel(new ImageIcon(mountainImg));

, , .

+2

: . Image.getScaledInstance(). . , , .

+1

All Articles