There is a JTable with columns in predifined order. Like
+———————-+
|id | name |age |
I want to move columns in the order (for example name=0, age=1, id=2).
+———————-+
|name | age | id |
How can i achive that?
JTable has method moveColumns, but unfortunately this is not enough. Assume order is strored in map:.
Map<String, Integer> columnOrder = getOrder();
for(Map.Entry<String, Integer> e : columnOrder.entrySet()) {
int columnIndex = jtable.convertColumnIndexToView(jtable.getColumn(e.getKey()).getModelIndex());
jtable.getColumnModel().moveColumn(columnIndex, e.getValue());
}
This does not work, because moveColumn also moves other columns, so from docu:
void moveColumn(int columnIndex,
int newIndex)
Moves the column and its header at columnIndex to newIndex. The old
column at columnIndex will now be found at newIndex. The column that
used to be at newIndex is shifted left or right to make room.
Can i (dynamically) somehow put the columns in the exactly same order as in my map?
The underlying problem is of course that
Vector, which is used in theDefaultTableColumnModelto store the columns and their order has no decent move support. The move is achieved as a remove and add, which triggers the “move left or right” behavior.You can however use this knowledge to simply move the columns in the correct order (from lowest index to highest index).
Starting from
to
can be achieved by first moving
nameto index 0. This will result in avector. If you then move age to index 1, it will do a remove first
followed by an insert at index 1
By making sure the element is always moved to the left side of its original position, you know how the shifting will behave.
Of course this depends on an implementation detail, but write a quick unit test to support your assumptions and use those implementation details (or write your own
TableColumnModel😉 )