简体   繁体   English

如何创建包含字符串和对象的Hashtable条目的JList?

[英]How can I create a JList that contains entries of a Hashtable of String and Object?

I want to create a JList that contains entries of a Hashtable of String and object : 我想创建一个包含Hashtable of String和object的条目的JList:

Hashtable<String,Object>

the JList element should contain the hashtable entry and display the value of the entry key that is a string ... JList元素应该包含哈希表条目并显示作为字符串的条目键的值...

Is it possible ? 可能吗 ? How can it be done ? 如何做呢 ?

Implement the ListModel interface by extending AbstractListModel . 通过扩展AbstractListModel实现ListModel接口。 Use the derived model to create your JList . 使用派生模型创建JList See also How to Use Lists . 另请参见如何使用列表

Use the keyset of your Hashtable for the data in your JList : 使用Hashtable的键集来获取JList的数据:

Hashtable<String, Object> table = new Hashtable<String, Object>();
JList list = new JList(table.keySet().toArray());

You can also call: 你也可以打电话:

list.setListData(table.keySet().toArray())

Hashtable is "old", so you should consider using a HashMap instead. Hashtable是“旧的”,因此您应该考虑使用HashMap。

You can get a Collection of all the values in the Hashtable by calling values(). 您可以通过调用values()来获取Hashtable中所有值的集合。 OOPS - I misread your question, change that to keySet(). OOPS - 我误读了您的问题,将其更改为keySet()。 If you are happy with displaying them in the JList using their toString() method (eg, they are Strings), just add them all to the JList. 如果您对使用toString()方法在JList中显示它们感到满意(例如,它们是字符串),只需将它们全部添加到JList即可。 Unfortunately, the JList constructors, at least in J6, do not take Collections (pet peeve of mine - how many years have Collections been around???), so you'll have to do a little work there. 不幸的是,JList构造函数,至少在J6中,并没有采用Collections(我的宠儿 - 多少年来Collections一直在哪里?),所以你必须在那里做一些工作。

One warning. 一个警告。 Hashtable and HashMap order their entries in a pretty unpredictable manner. Hashtable和HashMap以非常不可预测的方式对它们的条目进行排序。 So the order of the values in the JList will almost certainly not be the order you want. 因此,JList中值的顺序几乎肯定不是您想要的顺序。 Consider using a LinkedHashMap or a TreeMap to maintain a more reasonable ordering. 考虑使用LinkedHashMap或TreeMap来维护更合理的排序。

You can implement the ListModel interface to do anything you want. 您可以实现ListModel接口来执行任何操作。 Create a class that implements it and holds onto your desired HashMap. 创建一个实现它的类并保存到您想要的HashMap中。 Pay particular attention to the getElementAt method implementation. 特别注意getElementAt方法实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM