Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set order of columns in JTable

Tags:

java

jtable

I have a JTable with some columns. I have a HashMap of the column identifier mapped to the position in the 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 there is a function called moveColumn(A, B) within the JTable class. This moves a column from A to B, and B is putted left or right. My problem is, I want to order the whole table in a specific way, how can I do this? If I use moveColumn, I cannot know where B has been moved, in 5 out of 10 cases it might be the right side and in the other cases the wrong side.

Hope you understand my problem :-)

like image 554
Tobias Avatar asked Nov 12 '10 14:11

Tobias


2 Answers

You can change the columns order by removing all of them and adding them in the right 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]);
    }
}
like image 185
Guillaume Avatar answered Sep 30 '22 04:09

Guillaume


OK how about this. Might be a bit left field.

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

Next, extend DefaultTableColumnModel and store TableColumns in an ordered list.

Your JTable should now display columns according to their position. Untested but it sounds interesting so I might give it a go later.

like image 28
Qwerky Avatar answered Sep 30 '22 03:09

Qwerky