TITLE:BoxLayoutでリスト状に並べる
#navi(../)
RIGHT:Posted by [[terai]] at 2004-03-22
*BoxLayoutでリスト状に並べる [#n63d4aaf]
高さの異なるコンポーネントをスクロールできるようにリスト状に並べます。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#gefca96e]
#code{{
private final Box pnl = Box.createVerticalBox();
private final Vector<JComponent> list = new Vector<JComponent>();
public void addComp(JComponent c) {
  list.addElement(c);
  pnl.removeAll();
  for(JComponent tmp: list) {
    Dimension d = tmp.getPreferredSize();
    tmp.setMaximumSize(new Dimension(Integer.MAX_VALUE, d.height));
    pnl.add(tmp);
  }
  pnl.add(Box.createVerticalGlue());
  pnl.revalidate();
}
}}

**解説 [#b910d821]
上記のサンプルでは、Box.createVerticalBoxを使ってリスト状に並べています。この際、各コンポーネントの高さは変化せず、幅だけフレームサイズに追従するように、JComponent#setMinimumSizeを指定しています。

コンポーネントの高さの合計がフレームの高さより小さい場合は、下部に余白が出来るように、最後にBox.createVerticalGlueを追加しています。

// チュートリアルの[[How to Use SpringLayout (The Java™ Tutorials > Creating a GUI with JFC/Swing > Laying Out Components Within a Container)>http://java.sun.com/docs/books/tutorial/uiswing/layout/spring.html]]にある[[SpringUtilities.java>http://java.sun.com/docs/books/tutorial/uiswing/layout/examples/SpringUtilities.java]]を使用すると、サンプルのaddCompメソッドは以下のように書くこともできます。
//#code{{
//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]
- SpringLayoutではなく、BoxLayoutを使うようにサンプルを変更しました。 -- [[terai]] &new{2006-06-26 (月) 15:34:41};

#comment