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