TITLE:JTabbedPaneにタブを閉じるボタンを追加
#navi(../)
#tags(JTabbedPane, JButton)
RIGHT:Posted by &author(aterai); at 2007-01-29
* JTabbedPaneにタブを閉じるボタンを追加 [#j2e3f8ab]
``JDK 6``の新機能を使って``JTabbedPane``にタブを閉じるボタンを追加します。

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

#ref(https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTVCzHeo0I/AAAAAAAAAnA/hnMCEbHXnnw/s800/TabWithCloseButton.png)

** サンプルコード [#ebac5cc8]
#code(link){{
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);
  }
}
}}

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

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

** 参考リンク [#q5a6ecdb]
- [http://www.oracle.com/technetwork/articles/javase/index-135776.html More Enhancements in Java SE 6]
- [http://docs.oracle.com/javase/tutorial/uiswing/components/tabbedpane.html How to Use Tabbed Panes (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)]
- [[JTabbedPaneにタブを閉じるアイコンを追加>Swing/TabWithCloseIcon]]
- [[JTabbedPaneのTabTitleを左揃えに変更>Swing/TabTitleAlignment]]

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