且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建后按指定顺序设置JTable的列

更新时间:2022-12-10 09:58:46

潜在的问题当然是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 ;-) )