TITLE:JTabbedPaneのタブを等幅にしてタイトルをクリップ

Posted by terai at 2005-08-08

JTabbedPaneのタブを等幅にしてタイトルをクリップ

JTabbedPaneのタブを等幅にし、長いタイトルはクリップして表示します。

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

#screenshot

サンプルコード

final Insets tabInsets = UIManager.getInsets("TabbedPane.tabInsets");
tab1.setUI(new javax.swing.plaf.basic.BasicTabbedPaneUI() {
  @Override
  protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
    Insets insets = tabPane.getInsets();
    Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
    int width = tabPane.getWidth() - insets.left - insets.right
                                   - tabAreaInsets.left - tabAreaInsets.right;
    switch(tabPlacement) {
      case LEFT: case RIGHT:
        return (int)(width/4);
      case BOTTOM: case TOP: default:
        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) {
    Rectangle tabRect = rects[tabIndex];
    Rectangle rect = new Rectangle(textRect.x+tabInsets.left, textRect.y,
      tabRect.width-tabInsets.left-tabInsets.right, 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+tabInsets.left, textRect.y,
        tabRect.width-tabInsets.left-tabInsets.right, textRect.height);
      super.paintText(g, tabPlacement, font, metrics, tabIndex,
                      clippedText, rect, isSelected);
    }
  }
});

解説

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

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

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

タブの位置を左右にした場合、このサンプルでは全体の幅の1/4のタブ幅になるようにしています。

#screenshot(,screenshot1.png)


JDK 6 なら、JTabbedPaneのタイトルをクリップのように、JTabbedPane#setTabComponentAtメソッドを使って、JLabelのクリップ機能をそのまま利用する方法もあります。

参考リンク

コメント

  • tabAreaInsets を考慮するように修正しました。 -- terai