---
category: swing
folder: SortTabs
title: JTabbedPaneのタブをソート
tags: [JTabbedPane]
author: aterai
pubdate: 2006-04-24T15:47:22+09:00
description: JTabbedPaneのタブタイトルでその並び順をソートします。
image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTTe98QmaI/AAAAAAAAAkc/w7tzozy5FqM/s800/SortTabs.png
---
* 概要 [#summary]
`JTabbedPane`のタブタイトルでその並び順をソートします。

#download(https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTTe98QmaI/AAAAAAAAAkc/w7tzozy5FqM/s800/SortTabs.png)

* サンプルコード [#sourcecode]
#code(link){{
class SortAction extends AbstractAction {
  public SortAction(String label, Icon icon) {
    super(label, icon);
  }
  @Override public void actionPerformed(ActionEvent e) {
    setSortedTab(tab, makeSortedVector(tab));
  }
  private Vector makeSortedVector(JTabbedPane t) {
    Vector l = new Vector();
    for (int i = 0; i < t.getTabCount(); i++) {
      l.addElement(new ComparableTab(t.getTitleAt(i), t.getComponentAt(i)));
    }
    Collections.sort(l);
    return l;
  }
  private void setSortedTab(final JTabbedPane t, final Vector l) {
    t.setVisible(false);
    t.removeAll();
    for (int i = 0; i < l.size(); i++) {
      ComparableTab c = (ComparableTab) l.get(i);
      t.addTab(c.title, c.comp);
    }
    t.setVisible(true);
  }
  class ComparableTab implements Comparable {
    final public String title;
    final public Component comp;
    public ComparableTab(String title, Component comp) {
      this.title = title;
      this.comp  = comp;
    }
    @Override public int compareTo(Object o) {
      return this.title.compareTo(((ComparableTab) o).title);
    }
  }
}
}}

* 解説 [#explanation]
上記のサンプルでは、以下の手順でタブのソートを行っています。タブを追加、削除、ダブルクリックで名前変更などが可能なので、確認してみてください。

- ソートしたタブのリストを作成
- `JTabbedPane`から一旦タブをすべて削除
- ソート済みのリストから`JTabbedPane`にタブを戻す

//* 参考リンク [#reference]
* コメント [#comment]
#comment
#comment