Search code examples
javaswinglayout-managermiglayout

Java Miglayout wrap JPanels


I am trying to figure out why I can not wrap after adding a JPanel. My goal here is to have a class build my JPanels and then I will add it to the main screen with all JPanels stacked on one another. I can get this to work if I replace the JPanels with JLables. Here are my current results:

JPanel zPanel = new JPanel();
    for(int i = 0; i < zones.size(); i++ )
    {
        JLabel zLabel = new JLabel(zones.get(i));
        zPanel.add(zLabel);
        grid.add(zPanel,"wrap");
    }

Failed Test

And what I am trying to do:

for(int i = 0; i < zones.size(); i++ )
    {
        JLabel zLabel = new JLabel(zones.get(i));
        grid.add(zLabel,"wrap");
    }

Passed Test


Solution

  • If you're adding JLabel into JPanel, then you need to make it wrap inside the JPanel itself. And, add the zPanel when all of the children is populated.

    JPanel zPanel = new JPanel(new MigLayout("wrap 1");
    for(int i = 0; i < zones.size(); i++ )
    {
        JLabel zLabel = new JLabel(zones.get(i));
        zPanel.add(zLabel);
    }
    grid.add(zPanel,"wrap");