• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTabbedPaneのタブをソート
#navi(../)
RIGHT:Posted by &author(aterai); at 2006-04-24
*JTabbedPaneのタブをソート [#bb32089f]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2006-04-24~
更新日:&lastmod;

#contents

**概要 [#ib52ab9f]
JTabbedPaneのタブをソートします。

#screenshot

**サンプルコード [#ue218b7d]
#code{{
 class SortAction extends AbstractAction {
   public SortAction(String label, Icon icon) {
     super(label,icon);
   }
   public void actionPerformed(ActionEvent evt) {
     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;
     }
     public int compareTo(Object o) {
       return this.title.compareTo(((ComparableTab)o).title);
     }
   }
 }
}}
-&jnlp;
-&jar;
-&zip;

//#screenshot
#ref(http://lh4.ggpht.com/_9Z4BYR88imo/TQTTe98QmaI/AAAAAAAAAkc/w7tzozy5FqM/s800/SortTabs.png)

**サンプルコード [#ue218b7d]
#code(link){{
class SortAction extends AbstractAction {
  public SortAction(String label, Icon icon) {
    super(label,icon);
  }
  public void actionPerformed(ActionEvent evt) {
    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;
    }
    public int compareTo(Object o) {
      return this.title.compareTo(((ComparableTab)o).title);
    }
  }
}
}}

**解説 [#g820882f]
上記のサンプルでは、ソートしたリストを作成したあと、一旦タブをすべて削除し、リストからJTabbedPaneにタブを戻しています。

タブを追加、削除、ダブルクリックで名前変更して確認してみてください。

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