TITLE:JTabbedPaneのタブを等幅にしてタイトルをクリップ
#navi(../)
*JTabbedPaneのタブを等幅にしてタイトルをクリップ [#r616bd2a]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2005-08-08~
更新日:&lastmod;

#contents

**概要 [#fd7b15fa]
JTabbedPaneのタブを等幅にし、長いタイトルはクリップして表示します。

#screenshot

**サンプルコード [#z01f21c5]
#code{{
tab1.setUI(new javax.swing.plaf.basic.BasicTabbedPaneUI() {
  @Override
  protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
    int width = tabPane.getWidth() - 4;
    return (int)(width/tabPane.getTabCount());
  }
  @Override
  protected void paintText(Graphics g, int tabPlacement,
                           Font font, FontMetrics metrics, int tabIndex,
                           String title, Rectangle textRect, 
                           boolean isSelected) {
    int fw = (int) font.getSize();
    Rectangle tabRect = rects[tabIndex];
    Rectangle rect = new Rectangle(textRect.x+fw/2, textRect.y,
                                   tabRect.width-fw, textRect.height);
    String clippedText = SwingUtilities.layoutCompoundLabel(metrics, title, null,
                                    SwingUtilities.CENTER, SwingUtilities.CENTER,
                                    SwingUtilities.CENTER, SwingUtilities.TRAILING,
                                    rect, new Rectangle(), rect, 0);
    if(title.equals(clippedText)) {
      super.paintText(g, tabPlacement, font, metrics, tabIndex,
                      title, textRect, isSelected);
    }else{
      rect = new Rectangle(textRect.x+fw/2, textRect.y,
                           tabRect.width-fw, textRect.height);
      super.paintText(g, tabPlacement, font, metrics, tabIndex,
                      clippedText, rect, isSelected);
    }
  }
});
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#v0f32f18]
上記のサンプルでは、BasicTabbedPaneUI#calculateTabWidthメソッドをオーバーライドして、JTabbedPaneのタブ幅が、すべて等しくなるように設定しています。

タイトル文字列のほうが、このタブ幅より長い場合は、SwingUtilities.layoutCompoundLabelメソッドで文字列をクリップして表示します。

タイトルがクリップされていても、ツールチップで元の文字列を表示することができます。

//**参考リンク
**コメント [#y18543e1]
#comment