Search code examples
javaswingjpanellayout-managerborder-layout

Avoid JPanel from getting over another


I'm trying to load JPanels inside another but I can see only one, the others get hidden behind it. This is my code:

    pnlResultados.setLayout(new java.awt.BorderLayout());

    for (int i = 0; i < cantResultados; i++) {
        pResultado pr = new pResultado(modelo, resultados.get(i), padre, this);
        System.out.println("panel");
        pnlResultados.add(pr);
        pr.setVisible(true);
    }
    pnlResultados.setVisible(true);
    pnlResultados.revalidate();
    pnlResultados.repaint();

I have used System.out.printl to see how many pannels I'm creating and inserting and that seems alright. The problem is that they all get alocated in the same place, one over the other. How can I avoid this behaviour? Thank you


Solution

  • When you don't specify a constraint when adding a component to the BorderLayout, all components go to the CENTER. However, only the last component added will be visible.

    The solution is to use a different layout manager.

    Since you are adding components in a loop, I would suggest you might want to look at a GridLayout.

    Read the section from the Swing tutorial on Layout Managers for more information and working examples.

    You can always nest panels with different layout manager to achieve your desired layout.