---
category: swing
folder: EmptiesLastTableRowSorter
title: JTableのソートで空文字列を常に末尾にする
tags: [JTable, TableRowSorter, Comparator]
author: aterai
pubdate: 2020-02-17T15:39:55+09:00
description: JTableの空文字列を昇順・降順のどちらでソートしても常に末尾になるようなComparatorを設定します。
image: https://drive.google.com/uc?id=1l9euW_QP9-mgRVSkxLocJ5XBOWphL8a8
---
* Summary [#summary]
`JTable`の空文字列を昇順・降順のどちらでソートしても常に末尾になるような`Comparator`を設定します。
#download(https://drive.google.com/uc?id=1l9euW_QP9-mgRVSkxLocJ5XBOWphL8a8)
* Source Code Examples [#sourcecode]
#code(link){{
class RowComparator implements Comparator<String> {
protected final int column;
private final JTable table;
protected RowComparator(JTable table, int column) {
this.table = table;
this.column = column;
}
@Override public int compare(String a, String b) {
int flag = 1;
List<? extends RowSorter.SortKey> keys = table.getRowSorter().getSortKeys();
if (!keys.isEmpty()) {
RowSorter.SortKey sortKey = keys.get(0);
if (sortKey.getColumn() == column
&& sortKey.getSortOrder() == SortOrder.DESCENDING) {
flag = -1;
}
}
if (a.isEmpty() && !b.isEmpty()) {
return flag;
} else if (!a.isEmpty() && b.isEmpty()) {
return -1 * flag;
} else {
return a.compareTo(b);
}
}
}
}}
* Description [#explanation]
* Description [#description]
- `Comparator<String>#compare(...)`をオーバーライドして昇順の場合は「空文字列 < 文字列」、降順の場合は「空文字列 > 文字列」として常に空文字列以外が優先される`Comparator`を作成
-- この`Comparator`を`TableRowSorter#setComparator(...)`ですべての列に設定
-- `JTable`のソートでは`null`は内部でふるい落とされてしまうため、[https://docs.oracle.com/javase/jp/8/docs/api/java/util/Comparator.html#nullsFirst-java.util.Comparator- Comparator#nullsFirst(...)]などは使用しても無意味
--- `@Override public int compare(String a, String b)`の引数`a`、`b`が`null`になることはない
-- 空文字列ではなく`null`が設定されている場合、表示上は同一だが降順ソートすると`null`が先頭にきてしまう
* Reference [#reference]
- [[JTableでファイルとディレクトリを別々にソート>Swing/FileDirectoryComparator]]
* Comment [#comment]
#comment
#comment