无法将列比较器设置为JTable [英] Trouble setting a column comparator to a JTable
问题描述
在另一个线程中,我找到了这个比较器(post的底部),用于对JTable列进行排序,这些列可以由整数,字符串或两者组成。我无法弄清楚如何将它应用于我的JTable。我的表之前使用过自动创建的行排序器。我将其设置为false,我现在正在使用:
In another thread I found this comparator (bottom of post) for sorting JTable columns that could be composed of integers, strings, or both. I cannot figure out how to apply it to my JTable. My table was using the auto created row sorter before. I set that to false and I am now using:
TableRowSorter<MyTableModel> rowSorter = new TableRowSorter<MyTableModel>();
jtable.setRowSorter(rowSorter);
rowSorter.setComparator(0, c1);
我得到一个索引超出范围的例外,说我提供了无效的范围。我的表有多列。这是应用比较器的正确方法吗?我觉得这不是这样做的。
I get an index out of bounds exception saying I am providing an invalid range. My table has multiple columns though. Is this the correct way to apply the comparator? I feel like this is not the way to do it.
Comparator c1 = new java.util.Comparator() {
/**
* Custom compare to sort numbers as numbers.
* Strings as strings, with numbers ordered before strings.
*
* @param o1
* @param o2
* @return
*/
@Override
public int compare(Object oo1, Object oo2) {
boolean isFirstNumeric, isSecondNumeric;
String o1 = oo1.toString(), o2 = oo2.toString();
isFirstNumeric = o1.matches("\\d+");
isSecondNumeric = o2.matches("\\d+");
if (isFirstNumeric) {
if (isSecondNumeric) {
return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
} else {
return -1; // numbers always smaller than letters
}
} else {
if (isSecondNumeric) {
return 1; // numbers always smaller than letters
} else {
isFirstNumeric = o1.split("[^0-9]")[0].matches("\\d+");
isSecondNumeric = o2.split("[^0-9]")[0].matches("\\d+");
if (isFirstNumeric) {
if (isSecondNumeric) {
int intCompare = Integer.valueOf(o1.split("[^0-9]")[0]).compareTo(Integer.valueOf(o2.split("[^0-9]")[0]));
if (intCompare == 0) {
return o1.compareToIgnoreCase(o2);
}
return intCompare;
} else {
return -1; // numbers always smaller than letters
}
} else {
if (isSecondNumeric) {
return 1; // numbers always smaller than letters
} else {
return o1.compareToIgnoreCase(o2);
}
}
}
}
}
};
推荐答案
手动设置RowSorter时,你必须小心保持与模型同步:
when manually setting a RowSorter, you have to take care of keeping it in synch with the model yourself:
TableRowSorter sorter = new TableRowSorter();
table.setRowSorter(sorter);
sorter.setModel(table.getModel());
sorter.setComparator(myComparator);
这篇关于无法将列比较器设置为JTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!