• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTabbedPaneにタブを閉じるボタンを追加
#navi(../)
*JTabbedPaneにタブを閉じるボタンを追加 [#j2e3f8ab]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2007-01-29~
更新日:&lastmod;

#contents

**概要 [#n84777ff]
JDK 6 の新機能を使ってJTabbedPaneにタブを閉じるボタンを追加します。

#screenshot

**サンプルコード [#ebac5cc8]
#code{{
 class CloseButtonTabbedPane extends JTabbedPane {
   private final Icon icon;
   private final Dimension buttonSize;
   public CloseButtonTabbedPane(Icon icon) {
     super();
     //icon = new CloseTabIcon();
     this.icon = icon;
     buttonSize = new Dimension(icon.getIconWidth(), icon.getIconHeight());
   }
   public void addTab(String title, final JComponent content) {
     JPanel tab = new JPanel(new BorderLayout());
     tab.setOpaque(false);
     JLabel label = new JLabel(title);
     label.setBorder(BorderFactory.createEmptyBorder(0,0,0,4));
     JButton button = new JButton(icon);
     button.setPreferredSize(buttonSize);
     button.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
         removeTabAt(indexOfComponent(content));
       }
     });
     tab.add(label,  BorderLayout.WEST);
     tab.add(button, BorderLayout.EAST);
     tab.setBorder(BorderFactory.createEmptyBorder(2,1,1,1));
     super.addTab(null, content);
     setTabComponentAt(getTabCount()-1, tab);
   }
 }
class CloseButtonTabbedPane extends JTabbedPane {
  private final Icon icon;
  private final Dimension buttonSize;
  public CloseButtonTabbedPane(Icon icon) {
    super();
    //icon = new CloseTabIcon();
    this.icon = icon;
    buttonSize = new Dimension(icon.getIconWidth(), icon.getIconHeight());
  }
  public void addTab(String title, final JComponent content) {
    JPanel tab = new JPanel(new BorderLayout());
    tab.setOpaque(false);
    JLabel label = new JLabel(title);
    label.setBorder(BorderFactory.createEmptyBorder(0,0,0,4));
    JButton button = new JButton(icon);
    button.setPreferredSize(buttonSize);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        removeTabAt(indexOfComponent(content));
      }
    });
    tab.add(label,  BorderLayout.WEST);
    tab.add(button, BorderLayout.EAST);
    tab.setBorder(BorderFactory.createEmptyBorder(2,1,1,1));
    super.addTab(null, content);
    setTabComponentAt(getTabCount()-1, tab);
  }
}
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#h1ca2f51]
JDK 6 から追加されたタブにコンポーネントを配置する機能を使って、JButtonをタブに追加しています。

[[他の以前のサンプル>Swing/TabWithCloseIcon]]と比べると、簡単に実装できて、コードも短くなっています。
[[以前のサンプル>Swing/TabWithCloseIcon]]に比べると、実装も簡単でコードも短くなっています。

**参考リンク [#q5a6ecdb]
-[[More Enhancements in Java SE 6 (Mustang)>http://java.sun.com/developer/technicalArticles/J2SE/Desktop/mustang/enhancements/?feed=JSC]]
-[[JTabbedPaneにタブを閉じるアイコンを追加>Swing/TabWithCloseIcon]]

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