Terai Atsuhiro 2021-08-20 (金) 14:02:05

http://terai.xrea.jp/swing/springlayout/screenshot.png

public void addComp(JComponent label){
  SpringLayout layout = new SpringLayout();
  Component[] list = pnl.getComponents();
  if(list.length==0){
    layout.putConstraint(
          SpringLayout.WEST,label,0,SpringLayout.WEST,pnl);
    layout.putConstraint(
          SpringLayout.NORTH,label,0,SpringLayout.NORTH,pnl);
  }else{
    JComponent cmp = null;
    for(int i=0;i<list.length;i++){
      JComponent tmp = (JComponent)list[i];
      layout.putConstraint(
            SpringLayout.WEST,tmp,0,SpringLayout.WEST,pnl);
      if(cmp==null){
        layout.putConstraint(
              SpringLayout.NORTH,tmp,0,SpringLayout.NORTH,pnl);
      }else{
        layout.putConstraint(
              SpringLayout.NORTH,tmp,0,SpringLayout.SOUTH,cmp);
      }
      cmp = tmp;
    }
    layout.putConstraint(
          SpringLayout.WEST,label,0,SpringLayout.WEST,pnl);
    layout.putConstraint(
          SpringLayout.NORTH,label,0,SpringLayout.SOUTH,cmp);
  }
  pnl.add(label);
  pnl.setLayout(layout);
  initComps();
}
public void initComps(){
  Rectangle rv = scroll.getViewport().getViewRect();
  Insets ins = pnl.getInsets();
  int cw = (int)rv.getWidth() - ins.left - ins.right;
  int ch = 0;
  Component[] list = pnl.getComponents();
  for(int i=0;i<list.length;i++){
    JComponent tmp = (JComponent)list[i];
    int th = tmp.getPreferredSize().height;
    tmp.setPreferredSize(new Dimension(cw, th));
    ch = ch + th;
  }
  Dimension d = new Dimension(
                  (int)rv.getWidth(),ch+ins.top+ins.bottom);
  pnl.setPreferredSize(d);
  pnl.revalidate();
}

SpringForm

public void addComp2(JComponent cmp){
  pnl.add(cmp);
  Component[] list = pnl.getComponents();
  SpringUtilities.makeCompactGrid(pnl,
                                  list.length, 1, //rows, cols
                                  6, 6,           //initX, initY
                                  6, 6);          //xPad, yPad
  initComps();
}