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

Posted by terai at 2007-01-29

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

JDK 6 の新機能を使ってJTabbedPaneにタブを閉じるボタンを追加します。

  • &jnlp;
  • &jar;
  • &zip;

#screenshot

サンプルコード

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);
  }
}

解説

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

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

参考リンク

コメント