2

There are [too] many examples online of how to sort the Rows of a JTable by Column values.

Currently I am doing this by implementing AbstractTableModel and overridding getColumnClass to return the actual class of the data. Then calling setAutoCreateRowSorter.

How can I sort the Columns in a JTable by Row values?

2
  • This is not a duplicate. The above question is about sorting Rows, I want to sort Columns. Commented Mar 14, 2012 at 21:20
  • hmm .. don't quite understand what you are after, but as far as I do it's not supported in core: rows and columns are not semantically exchangeable. There are frameworks which support pivot tables, maybe they can be used, either directly or for inspiration Commented Mar 15, 2012 at 12:24

3 Answers 3

5

1) extract all value from TableHeader to the shortable Array (could be method in AbstractTableModel)

2) loop inside array and call

TableColumn column = table.getColumnModel().moveColumn(columnIndex, newIndex);

3) for all methods that used Model v.s. View (and vice versa) is required add

table/model#convertXxxIndexToXxx

4) for reset you have to create method in AbstractTableModel by calling

fireTableDataChanged(); or fireTableStructureChanged(); // not sure in this case

5) notice about above two fireTableXxxXxx

This can be a problem if you have added any custom renderers or editor to 
the table as you would lose them (by @camickr)
Sign up to request clarification or add additional context in comments.

Comments

0

Just define and set the RowSorter on your JTable. Here's a simple tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting

1 Comment

I want to sort the Columns not the Rows. RowSorters sort the rows.
-1

You can sort the values by clicking on a column header, if that's what you're asking.

3 Comments

I want to sort the Columns. When you click on the header it sorts the Rows.
I think there is no built-in function for that. You should sort by yourself, obtain the indexes and reset the column positions.
You can probably achieve that by implementing a hacked version of TableModel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.