创建后按指定顺序设置JTable的列 [英] Set columns of JTable in specified order after creation

查看:82
本文介绍了创建后按指定顺序设置JTable的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个JTable,其中的列按预定的顺序排列.喜欢

There is a JTable with columns in predifined order. Like

+ ---------------------- +

+----------------------+

| id |名称|年龄|

|id | name |age |

我想按顺序移动列(例如name = 0,age = 1,id = 2).

I want to move columns in the order (for example name=0, age=1, id=2).

+ ---------------------- +

+----------------------+

|名称|年龄| id |

|name | age | id |

我该如何实现? JTable有方法moveColumns,但是不幸的是,这还不够.假设订单存放在地图中:.

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

这不起作用,因为moveColumn也会移动其他列,因此从docu中获取:

This does not work, because moveColumn also moves other columns, so from docu:

void moveColumn(int columnIndex,
          int newIndex)

将列及其在columnIndex的标题移到newIndex.老人 现在,可在newIndex处找到columnIndex处的列.该列 向左或向右移动以腾出空间.

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?

推荐答案

潜在的问题当然是Vector,它在DefaultTableColumnModel中用于存储列,并且它们的顺序没有适当的移动支持.此举是通过删除和添加来实现的,它触发了向左或向右移动"的行为.

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

|id | name |age |

|name | age | id |

可通过先将name移至索引0来实现.这将导致

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

|name|id|age

向量.如果您随后将年龄移到索引1,则会先删除

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

|name|id

后跟索引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.

当然,这取决于实现细节,但是请编写一个快速的单元测试来支持您的假设并使用这些实现细节(或编写您自己的TableColumnModel ;-))

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

这篇关于创建后按指定顺序设置JTable的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆