• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTabbedPane風のタブ配置をレイアウトマネージャーで変更
#navi(../)
RIGHT:Posted by [[terai]] at 2009-06-08
*JTabbedPane風のタブ配置をレイアウトマネージャーで変更 [#hc561759]
CardLayoutとJRadioBUttonで作成したJTabbedPane風コンポーネントのタブ配置を自作レイアウトマネージャーで変更します。

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

#screenshot

**サンプルコード [#dbcd9376]
#code{{
class TabLayout implements LayoutManager, java.io.Serializable {
  public void addLayoutComponent(String name, Component comp) {}
  public void removeLayoutComponent(Component comp) {}
  public Dimension preferredLayoutSize(Container parent) {
    synchronized (parent.getTreeLock()) {
      Insets insets = parent.getInsets();
      int last = parent.getComponentCount()-1;
      int w = 0, h = 0;
      if(last>=0) {
        Component comp = parent.getComponent(last);
        Dimension d = comp.getPreferredSize();
        w = d.width;
        h = d.height;
      }
      return new Dimension(insets.left + insets.right + w,
                           insets.top + insets.bottom + h);
    }
  }

  public Dimension minimumLayoutSize(Container parent) {
    synchronized (parent.getTreeLock()) {
      return new Dimension(100, 24);
    }
  }

  public void layoutContainer(Container parent) {
    synchronized (parent.getTreeLock()) {
      Insets insets = parent.getInsets();
      int ncomponents = parent.getComponentCount();
      int nrows = 1;
      int ncols = ncomponents-1;
      //boolean ltr = parent.getComponentOrientation().isLeftToRight();

      if (ncomponents == 0) {
        return;
      }
      int lastw = parent.getComponent(ncomponents-1).getPreferredSize().width;
      int width = parent.getWidth() - (insets.left + insets.right) - lastw;
      int h = parent.getHeight() - (insets.top + insets.bottom);
      int w = (width>100*(ncomponents-1))?100:width/ncols;
      int gap = width - w*ncols;
      int x = insets.left;
      int y = insets.top;
      for (int i=0;i<ncomponents;i++) {
        int a = (gap>0)?1:0;
        gap--;
        int cw = (i==ncols)?lastw:w+a;
        parent.getComponent(i).setBounds(x, y, cw, h);
        x += w + a;
      }
    }
  }
  public String toString() {
    return getClass().getName();
  }
}
}}

**解説 [#l2903531]
上記のサンプルでは、以下のようなレイアウトマネージャーを作成してJRadioButtonをタブ風に並べています。

-最後のタブ(タブ追加ボタン)は常に幅固定
-最後のタブの高さがタブエリアの高さ
-タブエリアに余裕がある場合は、各タブ幅は100pxで一定
-タブエリアに余裕がない場合は、各タブ幅は均等
-タブエリアの幅に余裕がある場合は、各タブ幅は100pxで一定
-タブエリアの幅に余裕がない場合は、各タブ幅は均等

-その他
--タブを削除した場合、先頭タブにフォーカスが移動するようになっています。
--左のJButton(ダミー)は、タブエリアをラップするJPanel(BorderLayout)の東に配置しています。
--左のJButton(ダミー)は、タブエリアをラップするJPanel(BorderLayout)のBorderLayout.WESTに配置しています。

**参考リンク [#rea3e94d]
-[[CardLayoutを使ってJTabbedPane風のコンポーネントを作成>Swing/CardLayoutTabbedPane]]

**コメント [#n5459406]
#comment