• category: swing folder: TabWithCloseIcon title: JTabbedPaneにタブを閉じるアイコンを追加 tags: [JTabbedPane, Icon, JButton] author: aterai pubdate: 2006-03-20T12:44:58+09:00 description: JTabbedPaneにタブを閉じるためのアイコンやボタンを追加します。 image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTVFao3q4I/AAAAAAAAAnE/SarJyg-AIQk/s800/TabWithCloseIcon.png

概要

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の、タブにアイコンを表示する機能を利用
    • タブのクリックされた位置がアイコン上かどうかで、そのタブを閉じるかどうかを判断
  • CloseableTabbedPane(下)
    • JTabbedPaneWithCloseIconsの改良版
    • アイコンの位置、マウスがアイコン上に来たときの描画機能などを追加

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

参考リンク

コメント