Set column order in JTable

I have a JTable with some columns. I have a HashMap of a column id mapped to a position in a view, for example:

TableHeader1 | TableHeader2 | TableHeader3 sth. sth. sth. 

I know that:

 TableHeader1 -> position 0 TableHeader2 -> position 1 TableHeader3 -> position 2 

Now I want to reorder the columns. I know that in the JTable class there is a function moveColumn (A, B). This moves the column from A to B, and B moves left or right. My problem is that I want to arrange the whole table in a certain way, how can I do this? If I use moveColumn, I cannot know where B was moved, in 5 out of 10 cases it could be the right side, and in other cases the wrong side.

I hope you understand my problem :-)

+4
source share
4 answers

You can reorder columns by deleting all of them and adding them in the correct order:

 public static void setColumnOrder(int[] indices, TableColumnModel columnModel) { TableColumn column[] = new TableColumn[indices.length]; for (int i = 0; i < column.length; i++) { column[i] = columnModel.getColumn(indices[i]); } while (columnModel.getColumnCount() > 0) { columnModel.removeColumn(columnModel.getColumn(0)); } for (int i = 0; i < column.length; i++) { columnModel.addColumn(column[i]); } } 
+7
source

OK, how about this. Perhaps this is a little left field.

Extend the TableColumn and give your new class a position property. Add it Comparable and use position to compare columns.

Then continue with DefaultTableColumnModel and save the TableColumn in an ordered list.

Your JTable should now display the columns according to their position . Unverified, but that sounds interesting, so I could postpone it later.

+1
source

Based on @Guillaume's answer, I found a way to do this without having to delete all columns and add them again.

  public static void setColumnOrder(int[] indices, JTable table, TableColumnModel columnModel) { for (int i = 0; i < indices.length; i++) { columnModel.moveColumn(i, table.convertColumnIndexToView(indices[i])); } } 

This works better for me because with (SwingX) JXTable the order of the invisible columns does not change.

+1
source

If you want to reorder by column name, you can check the Table Column Reordering clause .

0
source

All Articles