TITLE:JTabbedPaneにタブを閉じるアイコンを追加
#navi(../)
RIGHT:Posted by [[terai]] at 2006-03-20
*JTabbedPaneにタブを閉じるアイコンを追加 [#x7fdca76]
JTabbedPaneにタブを閉じるためのアイコンやボタンを追加します。以下の参考リンクから引用したコードをほぼそのまま引用して紹介しています。

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

#screenshot

**サンプルコード [#b602abb2]
#code{{
public class JTabbedPaneWithCloseIcons extends JTabbedPane {
  public JTabbedPaneWithCloseIcons() {
    super();
    addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        tabClicked(e);
      }
    });
  }
  public void addTab(String title, Component component) {
    this.addTab(title, component, null);
  }
  public void addTab(String title, Component component, Icon extraIcon) {
    super.addTab(title, new CloseTabIcon(extraIcon), component);
  }
  private void tabClicked(MouseEvent e) {
    int index = getUI().tabForCoordinate(this, e.getX(), e.getY());
    if(index<0) return;
    Rectangle rect=((CloseTabIcon)getIconAt(index)).getBounds();
    if(rect.contains(e.getX(), e.getY())) {
      removeTabAt(index);
    }
  }
}
}}

**解説 [#p2450b3a]
-JTabbedPaneWithCloseButton(上)
>TabbedPaneLayoutを使用して、ボタンをタブの中にレイアウトしています。

-JTabbedPaneWithCloseIcons(中)
>JTabbedPaneには、タブにアイコンを表示する機能があるので、これを利用しています。タブのクリックされた位置がアイコン上かどうかで、そのタブを閉じるかどうかを判断しています。

-CloseableTabbedPane(下)
>JTabbedPaneWithCloseIconsの改良版です。アイコンの位置、マウスがアイコン上に来たときの描画機能などが追加されています。

上記のサンプルコードは、一番簡単なJTabbedPaneWithCloseIconsのものを掲載しています。

Java SE 6 では、JTabbedPaneのタブ部分に、文字列・アイコンに加えSwingコンポーネントが使えるようになっているので、上記のサンプルはもっと簡単に実現できるようになっています。
-[[JTabbedPaneにタブを閉じるボタンを追加>Swing/TabWithCloseButton]]
-[[Java SE 6 Mustangの新機能>http://www.02.246.ne.jp/~torutk/jvm/mustang.html]]

**参考リンク [#l8a5ea56]
-[[Swing [Archive] - Adding a close icon to a JTabbedPane tab>http://forums.sun.com/thread.jspa?threadID=239270]]
-[[Swing - JTabbedPane with close Icons>http://forums.sun.com/thread.jspa?threadID=337070]]
-[[Swing [Archive] - Closable Tab in JTabbedPane>http://forums.sun.com/thread.jspa?threadID=384894]]
-[[CloseAndMaxTabbedPane: An enhanced JTabbedPane>http://www.javaworld.com/javaworld/jw-09-2004/jw-0906-tabbedpane.html]]
-[[InfoNode - Java Components>http://www.infonode.net/index.html?itp]]
-[[Kirill Grouchnikov's Blog: Spicing up your JTabbedPane - part II>http://weblogs.java.net/blog/kirillcool/archive/2005/12/spicing_up_your_1.html]]
-[[JTabbedPaneでタブを追加削除>Swing/TabbedPane]]
-[[More Enhancements in Java SE 6>http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/enhancements/]]

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