Swing/SortTabs のバックアップの現在との差分(No.1)
TITLE:JTabbedPaneのタブをソート
JTabbedPaneのタブをソート
編集者:Terai Atsuhiro~
作成日:2006-04-24
更新日:2023-04-30 (日) 12:17:36
概要
JTabbedPane
のタブタイトルでその並び順をソートします。
Screenshot
Advertisement
概要
JTabbedPaneのタブをソートします。サンプルコード
#spanend
#spanadd
class SortAction extends AbstractAction {
#spanend
@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()));
}
#spanadd
}
#spanend
#spandel
#screenshot
#spanend
#spanadd
class ComparableTab {
#spanend
private final String title;
private final Component comp;
#spandel
**サンプルコード [#ue218b7d]
#spanend
class SortAction extends AbstractAction {
public SortAction(String label, Icon icon) {
super(label,icon);
}
public void actionPerformed(ActionEvent evt) {
final Vector list = makeSortedVector(tab);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
setSortedTab(tab, list);
}
});
}
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);
}
}
}
protected ComparableTab(String title, Component comp) {
this.title = title;
this.comp = comp;
}
-&jnlp;
-&jar;
-&zip;
public String getTitle() {
return title;
}
#spandel
**解説 [#g820882f]
#spanend
#spandel
上記のサンプルでは、ソートしたリストを作成したあと、一旦タブをすべて削除し、リストからJTabbedPaneにタブを戻しています。
#spanend
public Component getComponent() {
return comp;
}
#spanadd
}
#spanend
#spanadd
View in GitHub: Java, Kotlinコメント
解説
上記のサンプルでは、タブを追加、削除、ダブルクリックで名前変更してタブタイトルでのソートがテスト可能です。- タブのソートは以下の手順で実行
- ソートしたタブのリストを作成
-
JTabbedPane
から一旦タブをすべて削除 - ソート済みのリストから
JTabbedPane
にタブを戻す