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

▼魔方 西西 提交于 2019-12-10 13:17:26

问题


I want to create a JList that contains entries of a Hashtable of String and object :

Hashtable<String,Object>

the JList element should contain the hashtable entry and display the value of the entry key that is a string ...

Is it possible ? How can it be done ?


回答1:


Implement the ListModel interface by extending AbstractListModel. Use the derived model to create your JList. See also How to Use Lists.




回答2:


Use the keyset of your Hashtable for the data in your 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())



回答3:


Hashtable is "old", so you should consider using a HashMap instead.

You can get a Collection of all the values in the Hashtable by calling values(). OOPS - I misread your question, change that to keySet(). If you are happy with displaying them in the JList using their toString() method (e.g., they are Strings), just add them all to the 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.

One warning. Hashtable and HashMap order their entries in a pretty unpredictable manner. So the order of the values in the JList will almost certainly not be the order you want. Consider using a LinkedHashMap or a TreeMap to maintain a more reasonable ordering.




回答4:


You can implement the ListModel interface to do anything you want. Create a class that implements it and holds onto your desired HashMap. Pay particular attention to the getElementAt method implementation.



来源:https://stackoverflow.com/questions/8747458/how-can-i-create-a-jlist-that-contains-entries-of-a-hashtable-of-string-and-obje

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!