设置 JTable 中的列顺序
我有一个包含一些列的 JTable。我有一个映射到视图中位置的列标识符的 HashMap,例如:
TableHeader1 | TableHeader2 | TableHeader3
sth. sth. sth.
我知道:
TableHeader1 -> position 0
TableHeader2 -> position 1
TableHeader3 -> position 2
现在我想对列重新排序。我知道 JTable 类中有一个名为 moveColumn(A, B) 的函数。这会将一列从 A 移动到 B,并将 B 向左或向右放置。 我的问题是,我想以特定的方式对整个表进行排序,我该怎么做? 如果我使用 moveColumn,我无法知道 B 已移动到哪里,在十分之五的情况下,它可能是右侧,而在其他情况下可能是错误的一侧。
希望你理解我的问题:-)
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 :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以通过删除所有列并按正确的顺序添加它们来更改列顺序:
You can change the columns order by removing all of them and adding them in the right order:
好的,这个怎么样。可能有点左场。
扩展
TableColumn
并为您的新类提供一个position
属性。让它实现Comparable
并使用position
来比较列。接下来,扩展
DefaultTableColumnModel
并将TableColumn
存储在有序列表中。您的 JTable 现在应该根据列的位置来显示列。未经测试,但听起来很有趣,所以我稍后可能会尝试一下。
OK how about this. Might be a bit left field.
Extend
TableColumn
and give your new class aposition
property. Have it implementComparable
and use theposition
to compare columns.Next, extend
DefaultTableColumnModel
and storeTableColumn
s 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.根据@Guillaume 的回答,我找到了一种方法来做到这一点,而不需要删除所有列并再次添加它们。
这对我来说效果更好,因为使用 (SwingX) JXTable,不可见列的顺序不会被修改。
Based on @Guillaume answer I found a way to do that without the need to remove all columns and add them again.
This works better for me because with (SwingX) JXTable, the order of the invisible columns is not modified.
这个问题可以通过使用内置的 moveColumn 函数作为冒泡排序的快捷方式来解决。在这种情况下,哈希图保存你的权重。请记住,getColumnModel().getColumn(j).getModelIndex() 可以被视为不会更改的初始列索引/ID。将其视为列标题。
This problem can be solved by using the built in moveColumn function as a bubble sort shortcut. The hashmap holds your weights in that case. Keep in mind that getColumnModel().getColumn(j).getModelIndex() can be seen as the initial column index / ID that will not change. See it as a column title.
如果您想按列名称重新排序,则可以查看 表列重新排序建议。
If you want to reorder by column name then you can check out the Table Column Reordering suggestion.