javaswinglayout-managermiglayout

Scaling JPanels with Miglayout


I have one large JPanel that can have 0-4 JPanels added to it as rows.
I'm aiming to have the added Panels Scale to the size of the large Panel it's being added to (depending on how many panels are present)
1 Panel = 100% of the Panel
2 Panels = 50% of the Panel each
3 Panels = 33% of the Panel each
My jank solution was to divide the large panel into 12 set rows/cells (divisible by 3&4)

setLayout(new MigLayout("","[100%]","[8.3%][8.3%][8.3%][8.3%][8.3%][8.3%][8.3%][8.3%][8.3%][8.3%][8.3%][8.3%]")); 

and then depending on how many panels are added scale their span

if(count == 1){
 add(panel1, "cell 0 0, span 1 12, grow");
}
else if (count == 2){
add(panel1, "cell 0 0, span 1 6, grow");
add(panel2, "cell 0 6, span 1 6, grow");
...
...

This works... but is super ugly and I'm sure there must be an easier way.


Solution

  • I'm open GridLayout, but not sure how to implement.

    Why are you using the MigLayout when you don't even know how to use the basic layout managers provided in the JDK?

    There is no trick. You create a panel, set the layout and add the components to the panel.

    JPanel parent = new JPanel( new GridLayout(0, 1) );
    parent.add(child1);
    parent.add(child2);
    ,,,
    

    Read the Swing tutorial on Layout Managers for the basics of all the standard layout managers.