TITLE:JTabbedPaneにタブを閉じるボタンを追加
Posted by terai at 2007-01-29

JTabbedPaneにタブを閉じるボタンを追加

JDK 6 の新機能を使ってJTabbedPaneにタブを閉じるボタンを追加します。
  • category: swing folder: TabWithCloseButton title: JTabbedPaneにタブを閉じるボタンを追加 tags: [JTabbedPane, JButton] author: aterai pubdate: 2007-01-29T16:15:06+09:00 description: JDK 6の新機能を使用し、JTabbedPaneのタブ内に自身を閉じるためのボタンを追加します。 image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTVCzHeo0I/AAAAAAAAAnA/hnMCEbHXnnw/s800/TabWithCloseButton.png

概要

JDK 6の新機能を使用し、JTabbedPaneのタブ内に自身を閉じるためのボタンを追加します。

#screenshot

サンプルコード

#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
class CloseButtonTabbedPane extends JTabbedPane {
  private final Icon icon;
  private final Dimension buttonSize;
  public CloseButtonTabbedPane(Icon icon) {
    super();
    //icon = new CloseTabIcon();
    // icon = new CloseTabIcon();
    this.icon = icon;
    buttonSize = new Dimension(icon.getIconWidth(), icon.getIconHeight());
  }
  public void addTab(String title, final JComponent content) {
#spanadd

#spanend
  @Override 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));
    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) {
      @Override 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));
    tab.setBorder(BorderFactory.createEmptyBorder(2, 1, 1, 1));
    super.addTab(null, content);
    setTabComponentAt(getTabCount()-1, tab);
    setTabComponentAt(getTabCount() - 1, tab);
  }
}

解説

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

解説

  • JDK 6で追加されたJTabbedPane#setTabComponentAt(...)メソッドを使用して、指定したタブ内にJButtonを配置
    • JButtonActionListenerを追加し、クリックでJTabbedPane#removeTabAt(...)を実行してタブを削除
  • 以前のサンプルに比べると実装も簡単でコードも短くなる
以前のサンプルに比べると、実装も簡単でコードも短くなっています。

参考リンク

参考リンク

コメント

コメント