• 追加された行はこの色です。
  • 削除された行はこの色です。
---
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));
    JTabbedPane t = (JTabbedPane) getInvoker();
    List<ComparableTab> list = IntStream.range(0, t.getTabCount())
      .mapToObj(i -> new ComparableTab(t.getTitleAt(i), t.getComponentAt(i)))
      .sorted(Comparator.comparing(ComparableTab::getTitle))
      .collect(Collectors.toList());
    t.removeAll();
    list.forEach(c -> t.addTab(c.getTitle(), c.getComponent()));
  }
  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;
}

class ComparableTab {
  private final String title;
  private final Component comp;

  protected ComparableTab(String title, Component comp) {
    this.title = title;
    this.comp  = comp;
  }
  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);

  public String getTitle() {
    return title;
  }
  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);
    }

  public Component getComponent() {
    return comp;
  }
}
}}

* 解説 [#explanation]
上記のサンプルでは、ソートしたリストを作成したあと、一旦タブをすべて削除し、リストから`JTabbedPane`にタブを戻しています。
上記のサンプルでは、タブを追加、削除、ダブルクリックで名前変更してタブタイトルでのソートがテスト可能です。

タブを追加、削除、ダブルクリックで名前変更して確認してみてください。
- タブのソートは以下の手順で実行
+ ソートしたタブのリストを作成
+ `JTabbedPane`から一旦タブをすべて削除
+ ソート済みのリストから`JTabbedPane`にタブを戻す

//* 参考リンク [#reference]
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTabbedPane.html#removeAll-- JTabbedPane#removeAll() (Java Platform SE 8)]

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