• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JComponentをリスト状に並べる
#navi(../)
*JComponentをリスト状に並べる [#o44a3521]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-03-22~
更新日:&lastmod;
---
category: swing
folder: ComponentList
title: BoxLayoutでリスト状に並べる
tags: [BoxLayout, LayoutManager]
author: aterai
pubdate: 2006-06-15T19:34:32+09:00
description: 高さの異なるコンポーネントをスクロールできるようにリスト状に並べます。
image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTJ_UDZVaI/AAAAAAAAAVQ/BbW1hLhenS8/s800/ComponentList.png
---
* 概要 [#summary]
高さの異なるコンポーネントをスクロールできるようにリスト状に並べます。

#contents
#download(https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTJ_UDZVaI/AAAAAAAAAVQ/BbW1hLhenS8/s800/ComponentList.png)

**概要 [#k994c8ea]
高さの異なるコンポーネントをリスト状に並べてみます。
* サンプルコード [#sourcecode]
#code(link){{
private final Box box = Box.createVerticalBox();
private final Component glue = Box.createVerticalGlue();
public void addComp(JComponent comp) {
  comp.setMaximumSize(new Dimension(
      Short.MAX_VALUE, comp.getPreferredSize().height));
  box.remove(glue);
  box.add(Box.createVerticalStrut(5));
  box.add(comp);
  box.add(glue);
  box.revalidate();
  EventQueue.invokeLater(new Runnable() {
    @Override public void run() {
      comp.scrollRectToVisible(comp.getBounds());
    }
  });
}
}}

#screenshot
* 解説 [#explanation]
上記のサンプルでは、`Box.createVerticalBox()`で作成した`Box`にコンポーネントを追加してリスト状に並べています。

**サンプルコード [#gefca96e]
 private final Box pnl = Box.createVerticalBox();
 private final Vector list = new Vector();
 public void addComp(JComponent c) {
   list.addElement(c);
   pnl.removeAll();
   for(int i=0;i<list.size();i++) {
     JComponent tmp = (JComponent)list.get(i);
     Dimension d = tmp.getPreferredSize();
     tmp.setMaximumSize(new Dimension(Integer.MAX_VALUE, d.height));
     pnl.add(tmp);
   }
   pnl.add(Box.createVerticalGlue());
   pnl.revalidate();
 }
- 各コンポーネントの高さは変化せず幅だけフレームサイズに追従するように`JComponent#setMaximumSize(...)`を設定
- 各コンポーネントの高さの合計がフレームの高さより小さい場合は下部に余白が生成されるよう末尾に`Box.createVerticalGlue()`を追加

// 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();
//  }
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/Box.html Box (Java Platform SE 8)]

-&jnlp;
-&jar;
-&zip;
* コメント [#comment]
#comment
- `SpringLayout`ではなく、`BoxLayout`を使うようにサンプルを変更しました。 -- &user(aterai); &new{2006-06-26 (月) 15:34:41};
- 解説がソースと異なり、`setMinimumSize`となっていたのを`setMaximumSize`に修正。 -- &user(aterai); &new{2009-05-15 (金) 22:58:16};

**解説 [#b910d821]
// 上記のサンプルでは、SpringLayoutを使ってパネルにコンポーネントを並べています。右クリックのポップアップメニューから、高さの異なるラベルとボタンを追加することができます。追加されたコンポーネントの幅はJListのようにViewportに合わせて変化しますが、高さはsetPreferredSize()で設定されたものを維持します。
//
// チュートリアルの[[SpringForm>http://java.sun.com/docs/books/tutorial/uiswing/layout/example-1dot4/index.html#SpringForm]]にある[[SpringUtilities.java>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();
//  }

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

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

//**参考リンク
**コメント [#eec7c049]
- SpringLayoutではなく、BoxLayoutを使うようにサンプルを変更しました。 -- [[terai]] &new{2006-06-26 (月) 15:34:41};

#comment