更新时间:2023-12-04 19:25:52
总结我的各种评论:
因此,在包含可相互比较的值的列中不需要自定义比较器,只需实现columnClass即可返回该类型并完成操作.
So there is no need for a custom comparator in columns containing values that are comparable to each other, just implement the columnClass to return that type and be done.
这是一个演示行为的代码片段(将其放入您喜欢的测试设置中,任何框架都可以).第一列定义为可比较的整数,第二列定义为可比较的数字,其他只是对象.所有实际值均为整数.第一列按数字排序,所有其他列均按其字符串表示
Here's a snippet demonstrating the behaviour (throw it into you favourite test setup, just any frame will do). First column is defined as Integer which is-a Comparable, second as a Number which !is-a Comparable, others simply Object. All actual values are ints. The first column is sorted numerically, all others by their string representation
final Class[] classes = new Class[]{Integer.class, Number.class};
DefaultTableModel model = new DefaultTableModel(0, 3) {
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex < classes.length)
return classes[columnIndex];
return super.getColumnClass(columnIndex);
}
@Override
public String getColumnName(int column) {
return getColumnClass(column).getSimpleName();
}
};
for (int row = 0; row < 15; row++) {
model.addRow(new Object[]{row, row, row});
}
JTable table = new JTable(model);
table.setAutoCreateRowSorter(true);
如果实现columnClass(顺便说一句:应该在模型中完成,而不是在视图中完成!)在特定的上下文中似乎无法正常工作,则应该在其他地方跟踪一些问题(迟早会再次出现) )
If implementing the columnClass (btw: that should be done in the model, not the view!) appears to not be working in a concrete context, there's some problem elsewhere which should be tracked down (it will hit again sooner or later)