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にコンポーネントを追加してリスト状に並べています。

サンプルコード

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();
}
  • 各コンポーネントの高さは変化せず幅だけフレームサイズに追従するようにJComponent#setMaximumSize(...)を設定
  • 各コンポーネントの高さの合計がフレームの高さより小さい場合は下部に余白が生成されるよう末尾にBox.createVerticalGlue()を追加
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();
}

参考リンク

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

コメント