Question

I have a JTable that loads data from a database and then generates a summary row at the bottom of the table. I want the user to be able to sort the table, but I'd like the summary row to always remain at the bottom of the table.

I've been trying to create a custom TableRowSorter, but I'm having some trouble figuring it out and getting it to do what I want.

Anyone know how to do this? Thanks

Was it helpful?

Solution

You need a class which holds whether the value is a summary or not. Something like this

public class SummarizedValue {
  public Integer value;
  public boolean summarized;
  public String toString() { 
    return null == value? "" : value.toString();
  }
}

public class SummaryComparator implements Comparator<SummarizedValue> {
  public int compare(SummarizedValue v1, SummarizedValue v2) {
    if (v1.summarized) return 1;
    if (v2.summarized) return -1;
    return v1.value.compareTo(v2.value);
  }
}

public class SummaryBackComparator implements Comparator<SummarizedValue> {
  public int compare(SummarizedValue v1, SummarizedValue v2) {
    if (v1.summarized) return 1;
    if (v2.summarized) return -1;
    return v2.value.compareTo(v1.value);
  }
}

You need to display the objects of class SummarizedValue in your column and your row sorter should return SummaryComparator. Also your need to override toggle behaviour in RowSorter to use SummaryBackComparator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top