从 Java 中的哈希表填充 JTable
我有一个函数,它从用户那里获取密钥并生成哈希表(按照密钥指定的模式)。 创建 Hashtable 后,我想填充 JTable,以便每一列代表一个键,每行代表与该键关联的值。 我尝试了一切,但无法完成这项工作。 我没有从构造函数中创建表,因为我需要从用户那里获取输入。
I have a function which gets a key from the user and generates a Hashtable (on a pattern specified by the key). After creating a Hashtable, I would like to populate a JTable so that each each column represents a key and every rows represents the values associated with the key. I tried everything but couldn't get this work. I'm not creating the table from within the constructor as I need to get input from the user.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅如何使用表:创建表模型。
您基本上必须以上述方式包装哈希表。 这是一个例子。
See How to Use Tables: Creating a Table Model.
You basically have to wrap your hashtable in the above manner. Here's an example.
首先,避免使用
Hashtable
,直接使用Map
。 在这种情况下,您可能需要两种潜在的标准实现:LinkedHashMap
可以保留条目添加的顺序;TreeMap
是一个SortedMap
/NavigableMap
,将对结果进行排序(其顺序可以由Comparator
确定)。或者,您可能需要一种触发事件的Map
形式,或者如果您想要从
Map
到表的一次性转换 ,也可以提供TableModel
。 ,然后就非常简单了,只需使用这个预先填充的模型创建
JTable
(免责声明:我没有测试或编译此代码。)
保留
Map<。 /code> 和
没有基于索引的随机访问,因此对于大型地图,您需要要么聪明要么慢)。TableModel
同步的代码较多。通常,最好尽可能避免编写一个将自身公开为Map
和TableModel 的类。
,您可以通过触发事件的Map
和适应Map
的TableModel
(尽管请注意 < code>Map换句话说,一种更简单的方法是将数据直接添加到
DefaultTableModel
中,而根本不使用Map
。Firstly, avoid
Hashtable
, go straight forMap
. In this case there two potential standard implementations you mights want:LinkedHashMap
can retain the order that the entries were added;TreeMap
, aSortedMap
/NavigableMap
, will sort the results (order of which can be determined by aComparator
. Alternatively you might want a form ofMap
that fire events or also provides aTableModel
.If you want a one time conversion from the
Map
to table, then it's pretty straightforward.Then just create the
JTable
with this pre-populated model.(Disclaimer: I've not tested or so much as compiled this code.)
To keep the
Map
andTableModel
synchronized is more code. Generally it's best to avoid duplicating state whereever possible. Write a class that exposes itself as both aMap
and aTableModel
. You could go more disjoint by having aMap
that fires events and aTableModel
that adapts theMap
(although note thatMap
does not have random access based on index, so you'll need to be iether clever or slow for large maps).Going the other way, a simpler approach would be to add the data straight to a
DefaultTableModel
and not using aMap
at all.