TITLE:JTabbedPaneにタブを閉じるアイコンを追加

Posted by at 2006-03-20

JTabbedPaneにタブを閉じるアイコンを追加

`JTabbedPane`にタブを閉じるためのアイコンやボタンを追加します。以下の参考リンクから引用したコードをほぼそのまま引用して紹介しています。

  • &jnlp;
  • &jar;
  • &zip;
TabWithCloseIcon.png

サンプルコード

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);
    }
  }
}
View in GitHub: Java, Kotlin

解説

  • `JTabbedPaneWithCloseButton`(上)
    • `TabbedPaneLayout`を使用して、ボタンをタブの中にレイアウト
  • `JTabbedPaneWithCloseIcons`(中)
    • `JTabbedPane`の、タブにアイコンを表示する機能を利用
    • タブのクリックされた位置がアイコン上かどうかで、そのタブを閉じるかどうかを判断
  • `CloseableTabbedPane`(下)
    • `JTabbedPaneWithCloseIcons`の改良版
    • アイコンの位置、マウスがアイコン上に来たときの描画機能などを追加

`Java 1.6.0では、JTabbedPaneのタブ部分に、文字列・アイコンに加えSwing`コンポーネントが使えるようになっているので、上記のサンプルはもっと簡単に実現できるようになっています。

参考リンク

コメント