0

In my JTable, among other columns, I have a "Serial No" column which simply numbers the records in the table. I want this column to be fixed while I sort the rows by clicking on the JTable column headers. The sorting is happening alright, but the "Serial No" is getting mixed up in the process. Is there any way I could keep the "Serial No." column fixed while I sort the rows?

Thanks for your help on this.

Example:

SlNo Name
1 John
2 Peter
3 Alek

After sorting this by (clicking on 'Name' column), I get this:

SlNo Name
3 Alek
1 John
2 Peter

However, I would like the results as:

SlNo Name
1 Alek
2 John
3 Peter

user1639485
  • 808
  • 3
  • 14
  • 26
  • 1
    sure almost everything is possible, but no idea what do...., for better help sooner post an [SSCCE](http://docs.oracle.com/javase/tutorial/uiswing/index.html) demonstrated your issue with mixed output from `RowSorter` – mKorbel Sep 24 '12 at 06:44
  • don't quite understand: given rows with si == 0, 1, 2 ... after sorting another column you want to happen what? Keep that (like simple counting from top to bottom) as-is or make it jump to the now sorted rows (like an row identifier)? The latter is default, the former slightly unusual .. – kleopatra Sep 24 '12 at 08:20
  • 2
    thanks for the clarification :-) You might want to have a look at http://tips4java.wordpress.com/2008/11/18/row-number-table/ – kleopatra Sep 24 '12 at 08:52

2 Answers2

1

Have you tried implementing your own TableRowSorter?

Have a look at Sorting and Filtering

UPDATE

I've been digging around the code checking this out. It is doable, but you're going to have to reinvent the wheel to get it to work.

The default implementation simply compares row/column values together (getValueAt(row, column)) which is fine, but doesn't provide you with any context in order to make the decisions you need to make (ie, which row is been sorted, what the row value might be etc.), in fact the filter provides much more valuable information :P...

The method you really wan to override is private...(DefaultRowSorter.compare), but I'm not sure it will do what you want any way...

The only solution you have left is to implement you're solution from scratch (starting from RowSorter) that is capable of providing you with ALL the information you need in order to perform sub group sorting. Things like the table model, the row and columns been compared...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

A really simple implementation of this would be

public class siNo implements RowSorterListener {
    JTable table;
    public siNo(JTable table) {
        this.table = table;
    }

    @Override
    public void sorterChanged(RowSorterEvent e)
    {
        for (int i = 0; i < table.getRowCount(); i++) {
            table.setValueAt(Integer.toString(i+1), i, 0);
        }
    }
}

Your class which contains table

sorter.setSortable(0, false);
sorter.addRowSorterListener(new siNo());
Dan
  • 7,286
  • 6
  • 49
  • 114