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

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

#ref(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTVFao3q4I/AAAAAAAAAnE/SarJyg-AIQk/s800/TabWithCloseIcon.png)

** サンプルコード [#b602abb2]
#code(link){{
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 1.6.0``では、``JTabbedPane``のタブ部分に、文字列・アイコンに加え``Swing``コンポーネントが使えるようになっているので、上記のサンプルはもっと簡単に実現できるようになっています。

- [[JTabbedPaneにタブを閉じるボタンを追加>Swing/TabWithCloseButton]]
- [http://www.02.246.ne.jp/~torutk/jvm/mustang.html Java SE 6 Mustangの新機能]

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

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