AvrDragon
AvrDragon

Reputation: 7479

Set columns of JTable in specified order after creation

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?

Upvotes: 2

Views: 3792

Answers (2)

Robin
Robin

Reputation: 36601

The underlying problem is of course that Vector, which is used in the DefaultTableColumnModel to 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

|id | name |age |

to

|name | age | id |

can be achieved by first moving name to index 0. This will result in a

|name|id|age

vector. If you then move age to index 1, it will do a remove first

|name|id

followed by an insert at index 1

|name|age|id

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 ;-) )

Upvotes: 3

Related Questions