且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JTable无法正确排序Integers和Double值

更新时间:2023-12-04 19:25:52

总结我的各种评论:

  • TableRowSorter可以并且确实按预期对可比较类型进行排序
  • getColumnClass是为排序器提供正确排序方式的关键,因为它可以确定使用哪个默认Comparator
    • 如果 return 类型是Comparable,则它是委托给它的比较器实现
    • 如果 return 类型不是Comparable,则使用Collat​​or实例,并使用值的字符串表示形式,无论其 actual 类型是否为Comparable
    • TableRowSorter can and does sort Comparable types as expected
    • getColumnClass is the key to provide the sorter with the means of correct sorting as it determines which default Comparator is used
      • if the return type is a Comparable, it's a comparator implementation that delegates to it
      • if the return type is not a Comparable, the Collator instance is used and fed with the value's string representation, no matter whether it's actual type is Comparable or not

      因此,在包含可相互比较的值的列中不需要自定义比较器,只需实现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)