#navi(../)
*SpringLayoutでリスト状に並べる [#nc4396b2]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-03-22~
更新日:&lastmod;

#contents
**概要 [#k994c8ea]
高さの異なるコンポーネントをリスト状に並べてみます。

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

**サンプルコード [#gefca96e]
 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();
 }

-[[サンプルを起動>http://terai.xrea.jp/swing/springlayout/sample.jnlp]]
-[[jarファイル>http://terai.xrea.jp/swing/springlayout/sample.jar]]
-[[ソース>http://terai.xrea.jp/swing/springlayout/src.zip]]

**解説 [#b910d821]
上記のサンプルでは、SpringLayoutを使ってパネルにコンポーネントを並べています。右クリックのポップアップメニューから、高さの異なるラベルとボタンを追加することができます。追加されたこれらのコンポーネントの幅はJListのようにViewportに合わせて変化しますが、高さはsetPreferredSize()で設定されたものを維持します。

チュートリアルの[[SpringForm>http://java.sun.com/docs/books/tutorial/uiswing/layout/example-1dot4/index.html#SpringForm]]にある[[SpringUtilities>http://java.sun.com/docs/books/tutorial/uiswing/layout/example-1dot4/SpringUtilities.java]]を使うとサンプルのaddCompメソッドは、以下のように書くこともできます。
 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();
 }

//**参考リンク
**コメント [#eec7c049]
#comment