概要

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

サンプルコード

public class JTabbedPaneWithCloseIcons extends JTabbedPane {
  public JTabbedPaneWithCloseIcons() {
    super();
    addMouseListener(new MouseAdapter() {
      @Override 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のタブにアイコンを表示する機能を利用
    • JTabbedPaneMouseListenerを設定し、タブのクリックされた位置がアイコン上であればそのタブを閉じる
  • 下: CloseableTabbedPane
    • JTabbedPaneWithCloseIconsの改良版
    • アイコンの位置、マウスがアイコン上に来たときの描画機能などを追加

JDK 1.6.0では、JTabbedPaneのタブ部分にJTabbedPane#setTabComponentAt(Component)メソッドでComponentを設定可能になったので、上記のサンプルより手軽に同様の機能を実装できるようになりました。

参考リンク

コメント