TITLE:JComponentをリスト状に並べる

JComponentをリスト状に並べる

編集者:Terai Atsuhiro~

作成日:2004-03-22
更新日:2022-08-02 (火) 16:37:39
  • 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

概要

高さの異なるコンポーネントをスクロールできるようにリスト状に並べます。

概要

高さの異なるコンポーネントをリスト状に並べてみます。

サンプルコード

#spanend
#spanadd
private final Box box = Box.createVerticalBox();
#spanend
#spanadd
private final Component glue = Box.createVerticalGlue();
#spanend
#spanadd
public void addComp(JComponent comp) {
#spanend
  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());
    }
  });
#spanadd
}
#spanend
#spanadd
View in GitHub: Java, Kotlin

#screenshot

解説

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

サンプルコード

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()を追加

参考リンク

  • &jnlp;
  • &jar;
  • &zip;

コメント