Swing/SortTabs のバックアップの現在との差分(No.9)
- category: swing folder: SortTabs title: JTabbedPaneのタブをソート tags: [JTabbedPane] author: aterai pubdate: 2006-04-24T15:47:22+09:00 description: JTabbedPaneのタブタイトルでその並び順をソートします。 image:
概要
JTabbedPane
のタブタイトルでその並び順をソートします。
Screenshot
Advertisement
サンプルコード
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;
#spanadd
}
#spanend
#spanadd
#spanend
#spanadd
class ComparableTab {
#spanend
private final String title;
private final Component comp;
#spanadd
#spanend
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);
#spanadd
#spanend
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);
}
#spanadd
#spanend
public Component getComponent() {
return comp;
}
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、以下の手順でタブのソートを行っています。タブを追加、削除、ダブルクリックで名前変更などが可能なので、確認してみてください。 上記のサンプルでは、タブを追加、削除、ダブルクリックで名前変更してタブタイトルでのソートがテスト可能です。- ソートしたタブのリストを作成
-
JTabbedPane
から一旦タブをすべて削除 - ソート済みのリストから
JTabbedPane
にタブを戻す - タブのソートは以下の手順で実行
- ソートしたタブのリストを作成
-
JTabbedPane
から一旦タブをすべて削除 - ソート済みのリストから
JTabbedPane
にタブを戻す