javaswinglayout-managergrid-layout

Swing - After setVisible(false) white space remains


I have an outer JPanel that holds a list of inner panels in it, and my Layout is GridLayout

Under certain conditions, I want to render invisible some of my inner panels. The problem is, after I do setVisible(false) on some of my inner panels, they do disappear but their previous occupied space still remains and does not wipe out, therefore it creates white spaces.

How to remove those white spaces and make all visible inner panels to sort one after another without any white space in between them?

outerPanel.setLayout(new GridLayout(4, 1));
outerPanel.add(pnl1);
outerPanel.add(pnl2);
outerPanel.add(pnl3);
outerPanel.add(pnl4);

private void invisibleSome(){
 Component[] cmpts = outerPanel.getComponents();
   for(int i = 0; i< cmpts.length; i++){
       //this make some components invisible 
       //but their white space still remains
       cmpts[i].setVisible(i%2 == 0);
   }
}

Solution

  • I used BoxLayout and my problem solved :

    outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));